使用notifyAll恢复线程

时间:2011-01-19 01:08:16

标签: java

Pausing a Thread为例。如果我使用notifyAll代替通知,是否有任何副作用,是否有必要?

4 个答案:

答案 0 :(得分:6)

在那个例子中,它没有任何区别,因为只有1个线程在等待。

notifynotifyAll之间的区别在于后者会唤醒所有服务员,而不只是一个服务员。

答案 1 :(得分:1)

在“ Effective Java”第69项中,Bloch建议“始终使用notifyAll ”。

答案 2 :(得分:0)

如果您可以让多方等待对象,则使用no​​tifyAll而不是notify是很重要的。如果只有一个线程等待,则调用notify与notifyAll之间没有区别。

答案 3 :(得分:-1)

创建一个新的runnable。在run方法中,“start”countdownlatch正在等待并且不允许执行,除非在预定义的时间内使用该锁存器上的调用倒计时释放它。在这种情况下1.(因为start为1并发no)

//修订答案。 //一个可运行的类

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();
        }
    }

//这是执行工作线程的入口点方法。

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");
    }
相关问题