今天在和同事討論線程說到了這個我就實現了一把 直接貼代碼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