1、使用LockSupport实现:
public class T_TurnLockSupport {
private static final char[] nums = "123456".toCharArray();
private static final char[] chars= "ABCDEF".toCharArray();
static Thread N=null, C=null;
public static void main(String[] args) {
N = new Thread(()->{
for (char n:nums) {
System.out.print(n);
LockSupport.unpark(C);
LockSupport.park();
}
},"N");
C = new Thread(()->{
for (char c:chars) {
LockSupport.park();
System.out.print(c);
LockSupport.unpark(N);
}
},"C");
N.start();
C.start();
}
}
2、使用wait、notify实现:
public class T_TurnWaitNotify {
private static final Object lock = new Object();
private static final char[] nums = "123456789".toCharArray();
private static final char[] chars = "ABCDEFGHI".toCharArray();
public static void main(String[] args) {
new Thread(()->{
synchronized (lock){
for (char n : nums) {
System.out.print(n);
try {
lock.notify();//先唤醒另一个线程
lock.wait();//让出锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}, "N").start();
new Thread(()->{
synchronized (lock) {
for (char c : chars) {
System.out.print(c);
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}, "C").start();
}
}