栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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的值来唤醒线程进而实行另一个方法。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134562.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号