經典面試題——兩個線程交替打印奇數和偶數

今天在和同事討論線程說到了這個我就實現了一把 直接貼代碼html

public class Demo2 {
    private static volatile int i = 1;

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

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (obj) {
                    for (; i < 10; ) {
                        System.out.println(Thread.currentThread().getName() + " " + (i++));
                        try {
                            obj.notifyAll();
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    obj.notifyAll();
                }
            }
        };

        Thread t1 = new Thread(runnable, "打印偶數的線程 ");
        Thread t2 = new Thread(runnable, "打印奇數的線程 ");
        t2.start();
        t1.start();
    }
}

輸出結果java

打印奇數的線程 1
打印偶數的線程 2
打印奇數的線程 3
打印偶數的線程 4
打印奇數的線程 5
打印偶數的線程 6
打印奇數的線程 7
打印偶數的線程 8
打印奇數的線程 9
若有不對的地方,還請指教ide

原文地址 https://www.51csdn.cn/article...線程

相關文章
相關標籤/搜索