多线程交替打印数字

public class ThreadTest {
    private static int count = 1;

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();

        Runnable runnable = () -> {
            while (true) {
                synchronized (obj) {
                    obj.notify();

                    if (count > 100) {
                        break;
                    }

                    System.out.println(Thread.currentThread().getName() + " " + count);
                    count++;

                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();

        Thread.sleep(100_000);
    }
}

你可能感兴趣的:(基础)