java wait() notify()

使用wait方法可以使当前线程暂时停止运行
1. 线程处于就绪状态
2. 线程所获得的锁被释放,当有别有线程调用了对应的notify方法时,原线程可以重新获得锁,并运行。

典型的是生产者与消费者问题。

public class ProducerAndConsumer {

    // true 表示生产者不用工作
    public static boolean isEmpty = true;
    public static Object lock = new Object();

    public static void main(String[] args) {
        Thread producerThread = new Thread(new Producer());
        Thread consumerThread = new Thread(new Consumer());

        producerThread.start();
        consumerThread.start();
    }
}

class Producer implements Runnable {

    @Override
    public void run() {

        synchronized (ProducerAndConsumer.lock) {
            while (true) {
                if (!ProducerAndConsumer.isEmpty) {
                    try {
                        ProducerAndConsumer.lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("producer...");
                ProducerAndConsumer.isEmpty = false;
                ProducerAndConsumer.lock.notifyAll();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Consumer implements Runnable {

    @Override
    public void run() {
        synchronized (ProducerAndConsumer.lock) {
            while (true) {

                if (ProducerAndConsumer.isEmpty) {
                    try {
                        System.out.println("black is empty");
                        ProducerAndConsumer.lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("consumer...");
                ProducerAndConsumer.isEmpty = true;
                ProducerAndConsumer.lock.notifyAll();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37077950/article/details/81907323
今日推荐