版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
问题描述:
写两个线程,一个线程打印1~52,另一个线程打印字母A-Z , 打印顺序为12A34B56C……5152Z。
问题分析:
俩个线程是同步的,但当打印数字的线程打印了2个数字后,就进入等待队列,并且唤醒打印字母的线程;同理,打印字母的线程打印1个字母后,进入等待队列,并唤醒打印数字的线程
代码展示:
public class ThreadDemo {
Thread thread = new Thread(() -> {
synchronized (this) {
for (int i = 1; i <= 52; i++) {
System.out.print(i);
if (i % 2 == 0) {
this.notify();//唤醒下一个进程 (救队友)
try {
if (i!=52) this.wait();//这个等待 (自己跳井)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (this) {
for (int i = 65; i < 65 + 26; i++) {
System.out.print((char) i);
this.notify();//救队友
try {
if (i!=90)this.wait();//自己跳井 判断是为了最后使程序结束(否则打印完程序还在运行)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo();
demo.thread.start();
demo.thread2.start();
}
}