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();
    }
    }
  • 相关阅读:
    css 水平垂直居中总结
    计算机网络之应用层详解
    WPF 中 InitializeComponent 不存在解决方案
    [翻译]lithium 快速上手(QuickStart)
    [翻译]lithium 安装
    [翻译]lithium介绍
    [模板]离散化
    [总结]中位数及带权中位数问题
    [总结]Floyd算法及其应用
    [模板]SPFA判负环
  • 原文地址:https://www.cnblogs.com/kukai/p/12588941.html
Copyright © 2011-2022 走看看