多线程之——wait/notify

package thread.wait;

public class WaitTest {
    public static void main(String[] args) {
        PrintService printService = new PrintService();
        new Thread(printService::printChar).start();
        new Thread(printService::printNumber).start();
    }
}

class PrintService {
    private int number = 0;

    public PrintService() {}

    public void increment() {
        this.number = number + 1;
    }

    // 等待唤醒机制 wait,notify 必须和锁一起使用
    // 这是因为 等待还是唤醒是根据condition决定的 并且状态在线程间需要同步改变(假如两个线程看到的条件处于不一致状态 必然会产生混乱 那么根据条件来决定是否阻塞还是唤醒 就没有意义了)
    // 而使用同一把对象锁(就可以保证同一时间只能有一个线程修改条件) 线程间观测到的条件自然就是一致的
    public synchronized void printChar() {
        for (int i = 1; i <= 52; i+=2) {
            if(number % 2 != 0) { //跟 printNumber 条件相反
                try {
                    wait();
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
            System.out.println(i);
            System.out.println(i + 1);
            increment();//改变条件
            notify();
        }
    }

    public synchronized void printNumber() {
        for (int i = 65; i <= 90; i++) {
            if(number % 2 == 0) {
                try {
                    wait();
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
            System.out.println((char) i);
            increment();
            notify();
        }
    }
}

题目:创建两个线程, 交替打印数字和英文字母
12A34B56C… 52Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值