今天在和同事讨论线程说到了这个我就实现了一把 直接贴代码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