1. 使用LockSupport.park()
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;
public class Main {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) throws InterruptedException {
char[] array1 = "123456789".toCharArray();
char[] array2 = "ABCDEFGHI".toCharArray();
t1 = new Thread(()->{
for (int i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
LockSupport.unpark(t2); //让t2执行
LockSupport.park(); //自身停止
}
},"t1");
t2 = new Thread(()->{
for (int i = 0; i < array2.length; i++) {
LockSupport.park(); //自身停止
System.out.println(array2[i]);
LockSupport.unpark(t1); //让t1执行
}
},"t2");
t1.start();
t2.start();
}
}
2. 类似cas实现
public class Mian1 {
private enum ReadAndRun{ T1, T2 }
static volatile ReadAndRun readAndRun = ReadAndRun.T1;
public static void main(String[] args) {
char[] array1 = "123456789".toCharArray();
char[] array2 = "ABCDEFGHI".toCharArray();
new Thread(()->{
for (char c: array1) {
while( readAndRun != ReadAndRun.T1 ){ }
System.out.println(c);
readAndRun = ReadAndRun.T2;
}
},"t1").start();
new Thread(()->{
for (char c: array2) {
while( readAndRun != ReadAndRun.T2 ){ }
System.out.println(c);
readAndRun = ReadAndRun.T1;
}
},"t2").start();
}
}