线程练习--主线程执行10次,非主线程执行5次
public class Test { public static void main(String[] args){ MeThread me = new MeThread(); Thread t = new Thread(me); t.start(); boolean flag = true; int i = 1; synchronized (me) { while (flag) { System.out.println(Thread.currentThread().getName()+i); i++; if (i % 10 == 0) { try { me.notify();//Thread.currentThread().notifyAll(); i = 0; me.wait();//wait()必须放在notify()后边,先唤醒再自己暂停,不存在先暂停,再唤醒 } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("==========="); } } } } } } class MeThread implements Runnable { @Override public synchronized void run() { int i = 0; boolean flag = true; while (flag) { System.out.println(Thread.currentThread().getName() + i); i++; if (i % 5 == 0) { try { this.notify();//Thread.currentThread().notifyAll(); i = 0; this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("==========="); } } } } }
执行结果
main0
main1
main2
main3
main4
main5
main6
main7
main8
main9
===========
Thread-00
Thread-01
Thread-02
Thread-03
Thread-04
===========
main0
main1
main2
main3
main4
main5
main6
main7
main8
main9
===========
Thread-00
Thread-01
Thread-02
Thread-03
Thread-04
===========