public class Main {
public static void main(String[] args) {
final Object obj = new Object();
Thread a = new Thread(()->{
for(char i = 'A'; i <= 'Z'; ++i ) {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(i);
obj.notify();
}
}
});
Thread b = new Thread(()->{
for(int i = 1; i <= 52; i += 2) {
synchronized (obj) {
System.out.print(i);
System.out.print(i+1);
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
a.start();
b.start();
}
}
public class Test001 { public static void main(String[] args) { Object obj = new Object(); new Thread(() -> { synchronized (obj) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } int i = 1; while (i <= 52) { System.out.print(i); if (i % 2 == 0) { obj.notify(); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } i++; } } try { obj.wait(); for (int i = 1; i <= 52; i++) { if (i % 2 == 0) { obj.notify(); obj.wait(); } System.out.print(i); } } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { synchronized (obj) { char c = 'A'; while (c <= 'Z') { obj.notify(); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print(c++); } } }).start(); } }
/*** 写2个线程,其中一个线程打印1~52,另一个线程打印A~Z,打印顺序应该是12A34B56C...5152Z。