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

作者:时光spring 时间:2022-09-27 12:12:11 

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

来源:https://www.cnblogs.com/springa/p/12631483.html

标签:Java,线程,通信,wait,notify
0
投稿

猜你喜欢

  • 初识Spring Boot框架之Spring Boot的自动配置

    2022-08-25 10:27:57
  • springboot中bean的加载顺序问题

    2022-01-04 19:55:57
  • Java日常练习题,每天进步一点点(53)

    2023-08-12 00:55:00
  • 详解JAVA 强引用

    2021-11-06 18:38:16
  • Java 实现RSA非对称加密算法

    2021-08-19 16:27:51
  • Android DrawerLayout带有侧滑功能的布局类(1)

    2023-04-09 20:32:07
  • 浅谈几种常见语言的命名空间(Namespace)

    2022-11-13 12:17:42
  • JAVA得到数组中最大值和最小值的简单实例

    2023-03-18 01:19:39
  • java利用多线程和Socket实现猜拳游戏

    2022-10-03 08:03:30
  • C#调用webservice接口的最新方法教程

    2022-12-22 05:07:27
  • 一文了解Java读写锁ReentrantReadWriteLock的使用

    2023-10-12 19:28:21
  • 如何把char数组转换成String

    2023-11-11 07:38:15
  • JavaWeb 使用DBUtils实现增删改查方式

    2023-01-31 04:31:48
  • Spring Boot日志技术logback原理及配置解析

    2022-09-14 10:51:57
  • Java Thread之Sleep()使用方法及总结

    2023-11-16 10:38:35
  • C# using的本质及使用详解

    2022-10-10 06:11:23
  • 实战SpringBoot集成JWT实现token验证

    2022-10-07 15:57:49
  • 详解Spring如何解析占位符

    2023-11-27 12:44:46
  • C语言数据结构之二叉树详解

    2021-08-18 20:56:41
  • 二分查找算法在C/C++程序中的应用示例

    2021-06-01 08:15:30
  • asp之家 软件编程 m.aspxhome.com