notify 、wait线程之间的通信

2022/4/2 23:21:55

本文主要是介绍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();
    }
}

 



这篇关于notify 、wait线程之间的通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程