90 likes | 168 Views
Talking to Threads (and how they answer...). Corralling Threads. So you can create and synchronize threads... How do you control the threads you have? Look at java.lang.Thread API: Three sets of “control” methods: stop() , suspend() , resume() , destroy()
E N D
Corralling Threads • So you can create and synchronize threads... • How do you control the threads you have? • Look at java.lang.Thread API: • Three sets of “control” methods: • stop(), suspend(), resume(), destroy() • All deprecated or unimplemented. Bleh. • setDaemon(), setPriority() • Changes how scheduler prioritizes threads • yield(), sleep(), interrupt() • These are key control methods
yield() • Tells scheduler “I don’t need to run right now; let someone else go” • Use when waiting for data from another thread, when finished with a big computation and waiting to start next, etc. • Often, purpose better served with wait()
sleep() • Pauses thread for some time period • sleep(n) == pause for at least n milliseconds • Scheduler sets thread aside until time elapses, then puts back in schedule queue • Thread may wake up some random time after specified time • Good for delaying a thread for a while, doing something (roughly) periodically, etc.
interrupt() • Call on a thread to wake up thread, break out of a wait() state, etc. • Generates an InterruptedException on the thread when it is next scheduled (not instantly) • Caveat: only if thread is in a sleep() or wait() call
Control w/ sleep() and interrupt() Thread t=new Thread(new Runnable() { private void run() { boolean done=false; while (!done) { try { sleep(1000); } catch (InterruptedException e) { done=true; } } } } // somewhere else... t.interrupt();
wait()ing for Godot... • sleep(n) is good if you know how long you want to delay • What if a thread wants to wait indefinately, or for some other thread to do something? • Check out Object API: • Object o.wait() -- wait until some other object tells thread to wake up • o.notify() -- wake up one (random) thread that is waiting on o • o.notifyAll() -- wake up every thread that is waiting on o.
Yet more behind-the-scenes Java • Every Object in Java has a (single) “wait list”. • When a thread adds itself to an Object’s wait list, the thread suspends • Some other thread of execution can then call that object’s notify() method • One thread wakes up and can now take action • Does not generate an exception; does not change the status of a sleep()ing Thread • Must be synchronized on target object to wait() or notify() • Prevents collisions while messing w/ wait list
Use of wait lists DataBucket b; Thread t=new Thread(new Runnable(b) { public Runnable(DataBucket buck) { _bucket=b; } public void run() { while (!bored) { while (_bucket.isEmpty()) { synchronized(_bucket) { _bucket.wait(); } } _bucket.getData(); } }}); // elsewhere... b.addData(data); synchronized(b) { b.notify(); }