[Java编程] - 两个线程交替输出(A1B2C3D4...)

直接上代码
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

你可能感兴趣的:([Java编程] - 两个线程交替输出(A1B2C3D4...))