关于wait 和 notifyall的实用方法


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * User: guohaozhao 
 * Date: 13-7-11 10:44
 */
public class multiThreadTest {

    private static final byte[] lock = new byte[0];

    private static volatile boolean stop = false;

    private static class Notifier implements Runnable {

        @Override
        public void run() {
            try {
                System.out.println("Notifier is started ...");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }

            synchronized (lock) {
                lock.notifyAll();
                System.out.println("notified all !!");
            }

        }
    }

    private static class Waiter implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                try {
                    System.out.println(Thread.currentThread().getName() + "waiting ...");
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
            }
            while (!stop) {
                System.out.println(Thread.currentThread().getName() + "doing !!!");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public static void main(String... args) {

        CountDownLatch countDownLatch = new CountDownLatch(1);
        Thread thread = new Thread(new Notifier());
        thread.start();

        for (int i = 0; i < 3; i++) {
            Thread _thread = new Thread(new Waiter());
            _thread.start();
        }

        try {
            countDownLatch.await(10 * 1000, TimeUnit.MILLISECONDS);
            stop = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }

        System.out.println("test  done !!!");

    }
}



执行结果:
Notifier is started ...
Thread-2waiting ...
Thread-3waiting ...
Thread-4waiting ...
notified all !!
Thread-4doing !!!
Thread-3doing !!!
Thread-2doing !!!
Thread-4doing !!!
Thread-2doing !!!
Thread-3doing !!!
Thread-2doing !!!
Thread-3doing !!!
Thread-4doing !!!
test  done !!!

你可能感兴趣的:(notifyAll)