多线程依次打印

今天遇到一个面试题,

三个线程ABC依次循环打印1到100

面试的时候没写出来,回来想了想

public class Main {
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new MyRunnable(1));
        t1.setName("ta");
        Thread t2 = new Thread(new MyRunnable(2));
        t2.setName("tb");
        Thread t3 = new Thread(new MyRunnable(0));
        t3.setName("tc");

        t1.start();
        t2.start();
        t3.start();
    }
}

class MyRunnable implements Runnable {
    private int a;
    private static final Object o = new Object();
    private static volatile int i = 1;

    MyRunnable(int a) {
        this.a = a;
    }
    @Override
    public void run() {
        synchronized (o) {
            while (i <= 100) {
                if (i % 3 == a) {
                    System.out.println(Thread.currentThread().getName() + "--" + (i++));
                    o.notifyAll();
                } else {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

 

你可能感兴趣的:(学习)