经典面试题经典解法-两个线程交替执行

1.解法一

package com.gzz;

public class Tow_thread {

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (args) {
                wait(args);// 确保thread_B先执行
                for (int i = 1; i < 10; i++) {
                    args.notify();
                    System.out.print(i);
                    wait(args);
                }

            }
        }, "thread-A").start();
        new Thread(() -> {
            synchronized (args) {
                for (int i = 65; i < 74; i++) {
                    args.notify();
                    System.out.print((char) i);
                    wait(args);
                }
                args.notify();// 确保程序能正常结束
            }
        }, "thread-B").start();
    }

    private static void wait(Object o) {
        try {
            o.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.解法二

package com.gzz;

import java.util.concurrent.locks.LockSupport;

public class LockSupportTest {

    static Thread t1 = null;
    static Thread t2 = null;

    public static void main(String[] args) {
        t1 = new Thread(() -> {
            for (int i = 1; i < 10; i++) {
                LockSupport.unpark(t2);
                System.out.print(i);
                LockSupport.park();
            }
        });
        t2 = new Thread(() -> {
            for (int i = 65; i < 74; i++) {
                LockSupport.park();
                System.out.print((char) i);
                LockSupport.unpark(t1);
            }
        });
        t1.start();
        t2.start();
    }

}

你可能感兴趣的:(经典面试题经典解法-两个线程交替执行)