用两个线程,一个输出字母,一个输出数字,交替输出1A2B3C4D…26Z(线程之间的通信)
1.用synchronized,wait,notify
2.LockSupport,park,unpark
3.condtion,signal,await
下面是1,2两种方式实现
package com.example.future.test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
public class interview {
static Thread t1 = null,t2 = null;
public static void main(String[] args) throws Exception{
final Object o = new Object();
char[] c1 = "1234567".toCharArray();
char[] c2 = "ABCDEFG".toCharArray();
t1 = new Thread(() -> {
synchronized (o){
for (char c : c1){
System.out.println(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();//必须,否则无法停止程序
}
// for (char c : c1){
// System.out.println(c);
// LockSupport.unpark(t2);
// LockSupport.park();
// }
},"t1");
t2 = new Thread(() -> {
synchronized (o){
for (char c : c2){
System.out.println(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
// for (char c : c2){
// LockSupport.park();
// System.out.println(c);
// LockSupport.unpark(t1);
// }
},"t2");
t1.start();
t2.start();
// t1.run();
// t2.run();
}
}