首页 > 代码库 > Java并发:三个线程轮流打印十次abc

Java并发:三个线程轮流打印十次abc

方法1:用synchronized、wait、notifyAll实现

public class Main {
    static boolean t1Running = true;
    static boolean t2Running = false;
    static boolean t3Running = false;

    public static void main(String[] args) throws InterruptedException {
        final Object lock = new Object();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    synchronized (lock) {
                        while (!t1Running) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("a");
                        t1Running = false;
                        t2Running = true;
                        t3Running = false;
                        lock.notifyAll();
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    synchronized (lock) {
                        while (!t2Running) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("b");
                        t1Running = false;
                        t2Running = false;
                        t3Running = true;
                        lock.notifyAll();
                    }
                }
            }
        });
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    synchronized (lock) {
                        while (!t3Running) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        t1Running = true;
                        t2Running = false;
                        t3Running = false;
                        System.out.println("c");
                        lock.notifyAll();
                    }
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}

Java并发:三个线程轮流打印十次abc