线程通信

线程通信

wait(),notify(), notifyALL()方法

/*
* 线程通信例子:使用两个线程打印1-100,线程1和线程2交替打印
* 涉及到的三个方法:
     wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
     notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait, 就唤醒优先级高的
     notifyAll):一旦执行此方法,就会唤醒所有被wait的线程。

* 说明:1. wait(),notify(), notifyALL()三个方法必须使用在同步代码块或同步方法中。
*      2. wait(), notify(), notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视
            否则,会出现ILlegaLMonitorStateException异常
       3. wait(), notify(), notifyALL()三个方法是定义在java. lang. object类中。
* */
class Number implements Runnable {

    private int num = 1;

    @Override
    public void run() {
        while(true){
            synchronized(this){
                //调用notify()方法从阻塞线程中唤醒一个
                this.notify();
                if (num <= 100){
                    System.out.println(Thread.currentThread().getName()+":"+num);
                    num++;
                }else{
                    break;
                }

                //调用wait()方法使当前线程阻塞
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class CommunicationTest {
    public static void main(String[] args) {

        Number number = new Number();

        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }
}
posted @ 2022-03-19 17:09  路人假helloWorld  阅读(149)  评论(0)    收藏  举报