1. 使用LockSupport.park()

  1. import java.util.concurrent.CountDownLatch;
  2. import java.util.concurrent.locks.LockSupport;
  3. public class Main {
  4. static Thread t1 = null;
  5. static Thread t2 = null;
  6. public static void main(String[] args) throws InterruptedException {
  7. char[] array1 = "123456789".toCharArray();
  8. char[] array2 = "ABCDEFGHI".toCharArray();
  9. t1 = new Thread(()->{
  10. for (int i = 0; i < array1.length; i++) {
  11. System.out.println(array1[i]);
  12. LockSupport.unpark(t2); //让t2执行
  13. LockSupport.park(); //自身停止
  14. }
  15. },"t1");
  16. t2 = new Thread(()->{
  17. for (int i = 0; i < array2.length; i++) {
  18. LockSupport.park(); //自身停止
  19. System.out.println(array2[i]);
  20. LockSupport.unpark(t1); //让t1执行
  21. }
  22. },"t2");
  23. t1.start();
  24. t2.start();
  25. }
  26. }

2. 类似cas实现

  1. public class Mian1 {
  2. private enum ReadAndRun{ T1, T2 }
  3. static volatile ReadAndRun readAndRun = ReadAndRun.T1;
  4. public static void main(String[] args) {
  5. char[] array1 = "123456789".toCharArray();
  6. char[] array2 = "ABCDEFGHI".toCharArray();
  7. new Thread(()->{
  8. for (char c: array1) {
  9. while( readAndRun != ReadAndRun.T1 ){ }
  10. System.out.println(c);
  11. readAndRun = ReadAndRun.T2;
  12. }
  13. },"t1").start();
  14. new Thread(()->{
  15. for (char c: array2) {
  16. while( readAndRun != ReadAndRun.T2 ){ }
  17. System.out.println(c);
  18. readAndRun = ReadAndRun.T1;
  19. }
  20. },"t2").start();
  21. }
  22. }