其他分享
首页 > 其他分享> > notify 、wait线程之间的通信

notify 、wait线程之间的通信

作者:互联网

package com.cj.java1;

import java.util.concurrent.locks.ReentrantLock;

class Number implements Runnable{
    private int number = 1;
    private ReentrantLock lock = new ReentrantLock();
    public void run() {
        while (true){
            synchronized (this) {
                notify();
                if (number<100){

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() +":" +number);
                    number++;
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else{
                    break;
                }
            }

        }
    }
}

public class Communication {
    public static void main(String[] args) {
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}

 

标签:cj,synchronized,ReentrantLock,number,private,线程,notify,wait
来源: https://www.cnblogs.com/cciscc/p/16093927.html