Java-线程的通信

Java-线程的通信,第1张

Java-线程的通信 线程通信 方法
  • wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
  • notify():一旦执行此方法,就会唤醒被wait的一个线程,如果有多个线程被wait,就唤醒优先级高的线程。
  • notifyAll():一旦执行此方法,就会唤醒所有被wait的线程。
说明
  • 上述三个方法只能使用在同步代码块或同步方法当中。
  • 上述三个方法的调用者必须是同步代码块或同步方法中的同步监视器,否则会出异常。
示例
package com.threadT;

public class CommunicationTest {

    public static void main(String[] args) {
        Number number = new Number();
        Thread thread1 = new Thread(number);
        Thread thread2 = new Thread(number);

        thread1.setName("线程A");
        thread2.setName("线程B");
        thread1.start();
        thread2.start();
    }

}

class Number implements Runnable {

    private int number = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notifyAll();//唤醒wait()的线程

                if (number <= 100) {
                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;

                    try {
                        wait();//使得调用此方法的线程进入阻塞状态,wait()状态会释放锁。
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4669357.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-06
下一篇2022-11-06

发表评论

登录后才能评论

评论列表(0条)

    保存