阅读背景:

写两个线程,一个线程打印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();
}
// 打印数字的线程
Thread t



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: