多线程的wait和nofify方法的使用

wait():让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)

notify()和notifyAll():则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。

wait(long timeout): 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)

wait和notify实现线程间通信:

资源类:

public class Text {
    //内容
    public String content;
    //读写标记:true,可以读,false,可以写
    public boolean flag;
    //数字
    public int num;
}

读数据线程类:

public class ReadThread extends Thread {

    private Text text;

    public ReadThread(Text text) {
        this.text = text;
    }

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            synchronized (text) {
                if (text.flag) {
                    Thread.sleep(2000);
                    System.out.println("读到的内容为:" + text.content);
                    text.flag = false;
                    System.out.println("=============读取内容结束=============");
                    text.notify();
                }else{
                    text.wait();
                }
            }
        }
    }
}

写入线程实现类:

public class WriteThread extends Thread {

    private Text text;

    public WriteThread(Text text) {
        this.text = text;
    }

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            synchronized (text) {
                if (!text.flag) {
                    Thread.sleep(2000);
                    String name = "";
                    if (text.num % 2 == 0) {
                        name = "小则";
                    } else {
                        name = "小明";
                    }
                    text.num = text.num + 1;
                    text.content = name;
                    text.flag = true;
                    System.out.println("-------写入内容结束---------");
                    text.notify();
                } else {
                    text.wait();
                }
            }
        }
    }
}

线程启动类:

 public static void main(String[] args) throws InterruptedException {
        Text text = new Text();
        ReadThread readThread = new ReadThread(text);
        WriteThread writeThread = new WriteThread(text);
        writeThread.start();
        Thread.sleep(1000);
        readThread.start();
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值