JAVA线程通信

wait()

notify()

notifyAll()

1 只能用于synchronized 同步代码块和同步方法中

2 这几个方法的调用者,必须是同一个同步监视器

package com.LearnJava.Thread;

import java.util.concurrent.locks.ReentrantLock;

/*
    同步代码块
    synchronized(同步监视器){
        //需要同步的代码
    }
    同步监视器:俗称 锁,可以是任何实例化的类.但是需要共用同一个实例.
 */
class WindowSell implements Runnable{
    ReentrantLock lock = new ReentrantLock();
    private int ticket = 100;
    @Override
    public void run() {
        while (true) {
            synchronized(this){
                notify();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "sell " + ticket--);

                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else{
                    break;
                }
            }

        }
    }

}
public class ThreadTestTicket {
    public static void main(String[] args) {
        WindowSell win = new WindowSell();
        Thread t1 = new Thread(win);
        t1.setName("1号窗口");
        Thread t2 = new Thread(win);
        t2.setName("2号窗口");
        Thread t3 = new Thread(win);
        t3.setName("3号窗口");

        t1.start();
        t2.start();
        t3.start();
    }
}

 

posted @ 2020-02-08 15:54  超级学渣渣  阅读(112)  评论(0编辑  收藏  举报