欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-01-19 12:07:10|栏目:JAVA代码|点击:

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

上一篇:Java编程中正则表达式的用法总结

栏    目:JAVA代码

下一篇:判断List和Map是否相等并合并List中相同的Map

本文标题:Java多线程通信wait()和notify()代码实例

本文地址:http://www.codeinn.net/misctech/47679.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有