子執行緒迴圈10次,緊接著主執行緒迴圈100次,來回50次
阿新 • • 發佈:2019-02-11
package cn.test.thread; /* * 子執行緒10次,主執行緒100次,來回50次 */ public class ThreadTest1 { public static void main(String[] args) throws InterruptedException { ThreadTest1 tt = new ThreadTest1(); tt.init(); } public void init() throws InterruptedException { final Business bussiness = new Business(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 50; i++) { bussiness.subThread(); } } }).start(); Thread.sleep(1000); //此行為了讓主執行緒讓出CPU,讓子執行緒先執行 for (int i = 0; i < 50; i++) { bussiness.mainThread(); } } class Business { public synchronized void mainThread() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+" execute"+i); } this.notify(); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void subThread() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+" execute"+i); } this.notify(); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } }