zoukankan      html  css  js  c++  java
  • 线程通信示例

    线程通信:及线程交互
       用到的方法 wait(),notify()/notifyAll();
    wait():让当前线程进入阻塞状态,并释放锁。
    notify():唤醒一个被wait()的线程,如果多个线程,唤醒优先级最高的。
    notifyAll():唤醒所有被wait()的线程。

    注意: wait()、notify()、notifyAll()只能出现在同步代码块,同步方法中
      调用者必须是同步代码块或同步方法中的同步监视器相同
      否者会出现IllegalMonitorStateException异常
      wait()、notify()、notifyAll()定义在Java.lang包下
    示例:
    package thread;

    /**
    * @auto dh
    * @create 2020-03-28-17:02
    */
    class NumberDemo {
    private int number;

    public NumberDemo(int number) {
    this.number = number;
    }

    public void iterator1() {


    while (true) {
    synchronized (this) {
    this.notify();
    if (number <= 100) {
    System.out.println(Thread.currentThread().getName() + ":" + number);
    number++;
    }
    try {
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    }
    }
    }
    }

    class Test006 extends Thread {
    private NumberDemo numberDemo;

    public Test006(NumberDemo numberDemo) {
    this.numberDemo = numberDemo;
    }

    public void run() {
    this.numberDemo.iterator1();
    }
    }


    public class Thread006 {
    public static void main(String[] args) {
    NumberDemo numberDemo = new NumberDemo(0);
    Test006 ts = new Test006(numberDemo);
    ts.setName("线程一");
    Test006 ts2 = new Test006(numberDemo);
    ts2.setName("线程二");
    ts.start();
    ts2.start();
    }
    }
  • 相关阅读:
    2013-3 阿里性能稳定性沙龙
    8种Nosql数据库系统对比
    百度技术笔记之2013-1
    百度技术沙龙之2013-2&3
    【消息队列MQ】各类MQ比较
    Unity3D 游戏引擎之C#使用Socket与HTTP连接server数据传输包
    android的ndk学习(1)
    杭电 3555 Bomb
    FaceBook开源库Fresco
    SDUTOJ 2476Period
  • 原文地址:https://www.cnblogs.com/kukai/p/12588941.html
Copyright © 2011-2022 走看看