写两个线程,一个线程打印1-52,另一个线程打印字母A-Z顺序为12A34B。。。。。。。。(两个数字一个字母)

public class Work02 {

// 打印数字的线程
Thread th1 = new Thread(() -> {
    synchronized (this) {
        for (int i = 1; i < 53; i++) {
            System.out.println(i);
            if (i % 2 == 0) { // 判读i是否等于0,
                try {
                    this.notify();// 唤起下个线程
                    this.wait();// 等于0让该线程停止
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
});

// 打印字母的线程
Thread th2 = new Thread(() -> {
    synchronized (this) {
        for (int i = 0; i < 26; i++) {
            System.out.println((char) +(65 + i));
            this.notify();// 唤起其他线程
            try {
                Thread.sleep(1000);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

});

public static void main(String[] args) {
    Work02 w2 = new Work02();

    Thread th1 = new Thread();
    Thread th2 = new Thread();

    w2.th1.start();
    w2.th2.start();
}

}

*因为刚开始学习多线程好多地方不是太明白,看了好多帖子总结出来的(后期知道正确内容会上来改正的)
1:synchronized (this):可以理解为同步锁
2:notify();唤起处于等待的线程
3:wait():让该线程处于等待状态
代码也是按这样的步骤写的,先唤起在等待具体什么原因我也不太明白日后上来补充,有知道的大牛也可以评论告诉小弟

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值