Java多线程通信wait()和notify()代码实例

发布时间:2020-08-29 21:17:39 作者:时光spring
来源:脚本之家 阅读:120

1.wait()方法和sleep()方法:

wait()方法在等待中释放锁;sleep()在等待的时候不会释放锁,抱着锁睡眠。

2.notify():

随机唤醒一个线程,将等待队列中的一个等待线程从等待队列中移到同步队列中。

代码如下

public class Demo_Print {
  public static void main(String[] args) {
    Print p = new Print();
    new Thread() {
      public void run() {
        while (true) {
          p.print1();
        }
      };
    }.start();

    new Thread() {
      public void run() {
        while (true) {
          p.print2();
        }
      };
    }.start();
  }
}

class Print {
  int flag = 1;

  public synchronized void print1() {
    if (flag != 1) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("你");
    System.out.print("好");
    System.out.print("吗????????????");
    System.out.println();

    flag = 2;
    this.notify();
  }

  public synchronized void print2() {
    if (flag != 2) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("我");
    System.out.print("好");
    System.out.println();

    flag = 1;
    this.notify();
  }
}

在该案例中,实现一问一答的线程同步通信。当方法中开启了wait()方法后,通过改变flag的值来唤醒线程进而实行另一个方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 如何在Java中使用Varargs可变参数
  2. Java文件与类动手动脑实例详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 线程 通信

上一篇:SpringBoot学习之Json数据交互的方法

下一篇:Python使用uuid库生成唯一标识ID

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》