Home Listings By Name By Subject Email www.tomswan.com Help |
© 2001 by Tom Swan. All rights reserved.
Updated: 6/4/01 12:20:54 PM
Return to Listings page
Switch to Solutions by name page
Switch to Solutions by subject page
001: // Public fields 002: public final static int MIN_PRIORITY = 1; 003: public final static int NORM_PRIORITY = 5; 004: public final static int MAX_PRIORITY = 10; 005: 006: // Constructors 007: public Thread(); 008: public Thread(Runnable target); 009: public Thread(ThreadGroup group, Runnable target); 010: public Thread(String name); 011: public Thread(ThreadGroup group, String name); 012: public Thread(Runnable target, String name); 013: public Thread(ThreadGroup group, Runnable target, String name); 014: 015: // Public methods 016: public static native Thread currentThread(); 017: public static native void yield(); 018: public static native void sleep(long millis); 019: public static void sleep(long millis, int nanos); 020: private void init(ThreadGroup g, Runnable target, String name); 021: public synchronized native void start(); 022: public void run(); 023: private void exit(); 024: public void interrupt(); 025: public static boolean interrupted(); 026: public boolean isInterrupted(); 027: public final native boolean isAlive(); 028: public final void setPriority(int newPriority); 029: public final int getPriority(); 030: public final void setName(String name); 031: public final String getName(); 032: public final ThreadGroup getThreadGroup(); 033: public static int activeCount(); 034: public static int enumerate(Thread tarray[]); 035: public native int countStackFrames(); 036: public final synchronized void join(long millis); 037: public final synchronized void join(long millis, int nanos); 038: public final void join(); 039: public static void dumpStack(); // debugging only 040: public final void setDaemon(boolean on); 041: public final boolean isDaemon(); 042: public final void checkAccess(); 043: public String toString(); 044: public ClassLoader getContextClassLoader(); 045: public void setContextClassLoader(ClassLoader cl); 046: 047: // Deprecated methods -- DO NOT CALL! 048: public final void stop(); 049: public final synchronized void stop(Throwable obj); 050: public final void suspend(); 051: public final void resume();Return to top
001: import java.io.IOException; 002: 003: // Extend Thread class and provide a run() method 004: class Background extends Thread { 005: 006: boolean finished; // True when thread should die 007: 008: // Constructor 009: Background(String name) { 010: super(name); 011: finished = false; // Initialize run-flag 012: } 013: 014: // Called by start() to run the thread 015: public void run() { 016: try { 017: while (!finished) { // Loop "forever" 018: sleep(2000); 019: System.out.println("/nHurry up!"); 020: sleep(1000); 021: System.out.println("/nWhat's taking you so long?"); 022: sleep(1500); 023: System.out.println("/nC'mon, press that Enter key!"); 024: } 025: } catch (InterruptedException e) { 026: return; // End the thread 027: } 028: } 029: 030: // Halt the thread 031: public void halt() { 032: finished = true; // Cause while loop in run() to end 033: System.out.println("Stopping thread " + getName() + "/n"); 034: } 035: } 036: 037: // Main program class demonstrates background processing 038: class ThreadDemo { 039: public static void main(String args[]) { 040: 041: // Create the background thread 042: Background background = 043: new Background("Background process"); 044: System.out.println( 045: "Starting thread. Press Enter to stop."); 046: 047: // Start running the background thread 048: background.start(); 049: 050: // Simulate foreground process: wait for Enter key 051: try { 052: while ((char)System.in.read() != '/n') ; 053: } catch (IOException e) { 054: System.out.println(e.getMessage()); 055: } 056: 057: // Stop the background thread 058: background.halt(); 059: } 060: }Return to top
001: // The Runnable interface 002: public interface Runnable { 003: public abstract void run(); 004: }Return to top
001: import java.io.IOException; 002: 003: class Background implements Runnable { 004: 005: boolean finished = false; // True to end run() 006: int num = 3; // Prime number candidates 007: int delay; // Time between each output 008: 009: // Constructor 010: Background(int delay) { 011: this.delay = delay; 012: } 013: 014: // Return true if num is a prime number 015: public boolean isPrime(int n) { 016: for (int i = 2; i < n; i++) 017: if ((n % i) == 0) 018: return false; 019: return true; 020: } 021: 022: // Search for prime numbers in the background 023: public void run() { 024: try { 025: while (!finished) { 026: if (isPrime(num)) 027: System.out.println(num); 028: num++; 029: Thread.sleep(delay); 030: } // while 031: } catch (InterruptedException e) { 032: return; 033: } 034: } 035: 036: // Set flag to stop run() 037: public void halt() { 038: finished = true; 039: } 040: 041: } 042: 043: // Compute prime numbers in the background 044: class Primes { 045: 046: static char getChar() { 047: char ch = '/0'; 048: try { 049: ch = (char)System.in.read(); 050: } catch (IOException e) { 051: System.out.println(e.getMessage()); 052: } 053: return ch; 054: } 055: 056: static void waitForKey(char key) { 057: while (getChar() != key) /* wait */ ; 058: } 059: 060: public static void main(String args[]) throws Exception { 061: System.out.println("Press Enter to begin and again to quit"); 062: waitForKey('/n'); 063: // Construct and start thread 064: Background background = new Background(50); 065: Thread T = new Thread(background); 066: T.setPriority(4); 067: T.start(); 068: // Wait for Enter key while thread runs 069: waitForKey('/n'); 070: background.halt(); // Stop the thread 071: } 072: }Return to top
001: // Illustration only: not a complete program 002: public class SafetyClass { 003: 004: private int counter; // Private data in class 005: 006: // Thread-safe method to write data 007: public synchronized void setCounter(int n) { 008: counter = n; // Assign new value to counter 009: } 010: 011: // Thread-safe method to read data 012: public synchronized int getCounter() { 013: return counter; // Return counter's current value 014: } 015: }Return to top
001: import java.util.LinkedList; 002: 003: public class Queue { 004: 005: private LinkedList q = new LinkedList(); 006: 007: public synchronized void add(Object o) { 008: q.add(o); 009: } 010: 011: public synchronized Object get() 012: throws InterruptedException { 013: while (q.isEmpty()) 014: wait(); 015: return q.removeFirst(); 016: } 017: 018: public synchronized boolean isEmpty() { 019: return q.isEmpty(); 020: } 021: }Return to top
001: public class Job implements Runnable { 002: 003: private String name; // Name of this job 004: private int delay; // How long it takes to do this job 005: private boolean ready; // True when job is ready to be done 006: 007: // Constructor 008: Job(String name, int delay) { 009: this.name = name; 010: this.delay = delay; 011: ready = false; 012: new Thread(this).start(); // Job runs itself in a thread! 013: } 014: 015: // Run method called by thread scheduler 016: public void run() { 017: try { 018: doWhenReady(); // Do the job when it is ready 019: } catch (InterruptedException e) { 020: return; 021: } 022: } 023: 024: // Performs the job's actual work 025: // Because this calls wait(), code cannot be in run() 026: // and it must be synchronized on this object 027: private synchronized void doWhenReady() 028: throws InterruptedException { 029: while (!ready) 030: wait(); // Wait indefinitely until ready 031: // Simulate the job by displaying messages and sleeping 032: // for the amount of time this job takes 033: System.out.println("/nStarting " + name); 034: System.out.println("Time = " + delay / 1000 + " second(s)"); 035: Thread.currentThread().sleep(delay); // Simulate job runtime 036: System.out.println("/nFinishing " + name); 037: System.out.println("Ending thread " + toString()); 038: } 039: 040: // Set the thread state flag to true 041: // and notify all threads of the change 042: public synchronized void doJob() { 043: ready = true; 044: notifyAll(); 045: } 046: }Return to top
001: import Queue; 002: import Job; 003: 004: class Server implements Runnable { 005: 006: Queue q = new Queue(); // Construct our Queue object 007: 008: public void run() { 009: try { 010: doWhenReady(); // Do the server's activities 011: } catch (InterruptedException e) { 012: return; 013: } 014: } 015: 016: // Perform server activities until shutdown 017: private synchronized void doWhenReady() 018: throws InterruptedException { 019: for (;;) { // Do "forever" loop 020: while (q.isEmpty()) // Wait until there is a job in 021: wait(); // the queue 022: Job j = (Job)q.get(); // Get the job 023: j.doJob(); // Do the job 024: } // for 025: } 026: 027: // Add a new job to the server's queue 028: // This returns immediately; the job is not performed 029: // until the server thread detects the queue is no longer 030: // empty. 031: public synchronized void add(Job j) { 032: q.add(j); 033: notifyAll(); 034: } 035: }Return to top
001: import java.util.Random; 002: import Job; 003: import Server; 004: 005: class Client implements Runnable { 006: 007: Random rand = new Random(); 008: boolean finished = false; 009: int jobcount = 0; 010: 011: // Utility method creates a new numbered job with 012: // a random time delay to simulate how long the job takes 013: private Job getAJob() { 014: String name = "Job #" + ++jobcount; 015: int delay = 1000 + rand.nextInt(9000); // 1 .. 10 seconds 016: Job j = new Job(name, delay); 017: return j; 018: } 019: 020: public void run() { 021: 022: // Create the server daemon thread 023: Server server = new Server(); 024: Thread T = new Thread(server); 025: T.setDaemon(true); // Server is a daemon! 026: T.start(); // Start the server thread running 027: 028: // Main run() actions 029: try { 030: while (!finished) { 031: 032: // Create a job and pass it to the server 033: Job j = getAJob(); // Create simulated job object 034: server.add(j); // Returns immediately 035: 036: // Simulate user activity by sleeping a random time 037: int time = 1000 + rand.nextInt(5000); 038: System.out.println("Sleeping for " + 039: time / 1000 + " second(s)"); 040: Thread.currentThread().sleep(time); 041: 042: } 043: } catch (InterruptedException e) { 044: return; 045: } 046: } 047: 048: // Halt the client 049: // However, all job threads finish to completion! 050: public synchronized void halt() { 051: finished = true; 052: notifyAll(); 053: } 054: }Return to top
001: import java.io.IOException; 002: import java.util.*; 003: import Client; 004: 005: class LockDemo { 006: 007: // Get a character from keyboard 008: static char getChar() { 009: char ch = '/0'; 010: try { 011: ch = (char)System.in.read(); 012: } catch (IOException e) { 013: System.out.println(e.getMessage()); 014: } 015: return ch; 016: } 017: 018: // Wait for user to press a specified key 019: static void waitForKey(char key) { 020: while (getChar() != key) /* wait */ ; 021: } 022: 023: public static void main(String args[]) { 024: 025: // Construct and start the client (job creator) thread 026: Client client = new Client(); 027: new Thread(client).start(); 028: 029: // Wait for Enter key so threads can run 030: System.out.println("/n<<< Press Enter to end program >>>/n"); 031: waitForKey('/n'); // All threads run while waiting 032: 033: // Halt the client thread; sever daemon also ends 034: // However, any remaining job threads finish to completion! 035: client.halt(); 036: } 037: }Return to top