测试wait和notify

(想在网上找一个wait和notify的代码例子,发现有个缺陷,如果没有中间睡眠的5秒,那么线程1完全不需要notify,因为线程2走不到wait。我做了改进,可以让两个线程进行来回唤醒。)正确代码在下面自取。

为保持线程可见,应该在count上加上volatile。只要看懂下面的代码,再去百度一下wait和sleep的区别,就应该就不用去背了。我理解,java八股文就应该理解性去记忆。
package test;

public class GreatNickName {

    private volatile int count = 0;
    private Object lock = new Object(); // 锁对象

    public synchronized void increment() throws InterruptedException {
        while (count == 0) { // 当count为0时,等待被通知
            wait();
        }
        count++;
        try {
            Thread.sleep(5000); // 模拟任务执行时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " incremented to " + count);
        notify(); // 唤醒可能正在等待的线程
    }

    public synchronized void decrement() throws InterruptedException {
        while (count!= 0) { // 当count大于0时,等待变为0
            wait();
        }
        count--;
        try {
            Thread.sleep(5000); // 模拟任务执行时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " decremented to " + count);
        //notify(); // 唤醒其他线程
    }

    public static void main(String[] args) {
        GreatNickName resource = new GreatNickName();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    resource.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    Thread.sleep(100); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    resource.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    Thread.sleep(100); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值