写两个线程,一个线程打印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():让该线程处于等待状态
代码也是按这样的步骤写的,先唤起在等待具体什么原因我也不太明白日后上来补充,有知道的大牛也可以评论告诉小弟

猜你喜欢

转载自blog.csdn.net/weixin_42337796/article/details/81812283