[Java编程] - 两个线程交替输出(A1B2C3D4...)
2021-03-26 本文已影响0人
夹胡碰
直接上代码
public class Test55 {
static Thread th1, th2;
public static void main(String[] args) {
String a = "abcdefg";
String b = "123456789";
th1 = new Thread(() -> {
for (char c : a.toCharArray()) {
System.out.print(c);
LockSupport.unpark(th2);
LockSupport.park();
}
});
th2 = new Thread(() -> {
for (char c : b.toCharArray()) {
LockSupport.park();
System.out.print(c);
LockSupport.unpark(th1);
}
});
th1.start();
th2.start();
}
}
输出
a1b2c3d4e5f6g7