问题
两个线程,一个输出字母,一个输出数字,交替出现比如:1A2B3C4D5E6F…
代码实战
-
LockSupport方式
public class LockSupportMethod { static Thread t1 = null; static Thread t2 = null; public static void main(String[] args) { char[] cI = "123456".toCharArray(); char[] aC = "ABCDEF".toCharArray(); t1 = new Thread(() -> { for (char i : cI) { System.out.printf(String.valueOf(i)); LockSupport.unpark(t2); LockSupport.park(); } }, "t1"); t2 = new Thread(() -> { for (char a : aC) { LockSupport.park(); System.out.printf(String.valueOf(a)); LockSupport.unpark(t1); } }, "t2"); t1.start(); t2.start(); } }
-
Cas模式实现
public class CasMethod { enum Status { T1, T2} volatile static Status status = Status.T1; public static void main(String[] args) { char[] cI = "123456".toCharArray(); char[] aC = "ABCDEF".toCharArray(); new Thread(() -> { for (char i : cI) { while (!Status.T1.equals(status)) { } System.out.printf(String.valueOf(i)); status = Status.T2; } }, "t1").start(); new Thread(() -> { for (char a : aC) { while (!Status.T2.equals(status)) { } Syste