Resuming a thread by using notifyAll
Ta开发者_高级运维ke the Pausing a Thread example. If I use notifyAll
instead of notify, is there any side effect, and is it necessary?
In that example, it will not make any difference, because there's only 1 thread waiting.
The difference between notify
and notifyAll
is that the latter wakes all waiters, instead of just one.
In “Effective Java” item 69, Bloch suggests “always use notifyAll”.
Using notifyAll as opposed to notify is important if you can have multiple parties waiting on the object. If only one thread ever waits, then there is no difference between calling notify vs notifyAll.
Create a new runnable. In the run method "start" countdownlatch is waiting and will not allow execution unless it is released using calling countdown on that latch for a predefined time. In this case 1. (since start is passed 1 as concurrent no)
// Revised Answer. // A runnable class.
public class WorkerThread implements Runnable
{
CountDownLatch start;
CountDownLatch end;
String name;
WorkerThread(CountDownLatch startLatch, CountDownLatch stopLatch)
{
this.start = startLatch;
this.end = stopLatch;
}
public void run()
{
try
{
start.await();
} catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("Will run when start is released ");
end.countDown();
}
}
// This is the entry point method that executes the worker thread.
public void initiateProcess (final int count) {
CountDownLatch start = new CountDownLatch(1);
CountDownLatch stop = new CountDownLatch(count);
for (int i = 0; i < count; i++)
{
new Thread(new WorkerThread(start, stop))
.start();
}
System.out.println("Go");
// This is where start latch is released. Now worked thread can complete its function.
start.countDown();
try
{
// Stop will wait until stop latch is countdowned to zero from count param. (see count param)
stop.await();
} catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("Finished");
}
精彩评论