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();
}
}
两个线程,一个为123456,一个为ABCDEF、交替打印出1A2B3C...
原文:https://www.cnblogs.com/tengri-fighting/p/12780817.html