java兩個執行緒交替執行
阿新 • • 發佈:2019-01-05
/* * Copyright (c) 2014 Qunar.com. All Rights Reserved. */ /** * @author: wangh.wang Date: 2015/7/22 Time: 21:15 */ public class Thread1 { public static void main(String args[]) { final Bussiness business = new Bussiness(); Thread a=new Thread(new Runnable(){ @Override public void run(){ business.SubThread(); } }); Thread b=new Thread((new Runnable() { @Override public void run() { business.MainThread(); } })); a.start(); b.start(); } } class Bussiness { private static Object LOCK = new Object(); volatile boolean bShouldSub = true;//這裡相當於定義了控制該誰執行的一個訊號燈 public void MainThread() { for (int i = 0; i < 50; i++) { synchronized (LOCK) {//notify和wait的物件一定要和synchronized的物件保持一致 for (int j = 0; j < 10; j++) { System.out.println(Thread.currentThread().getName() + "+MainThread:i=" + i + ",j=" + j); } if (bShouldSub) { bShouldSub = false; LOCK.notify(); if(i<49){ try { LOCK.wait(); }catch (InterruptedException e) { // TODO Auto-generatedcatch block e.printStackTrace(); } } } } } } public void SubThread() { for (int i = 0; i < 50; i++) { synchronized (LOCK){ for (int j = 0; j < 5; j++) { System.out.println(Thread.currentThread().getName() + "+SubThread:i=" + i + ",j=" + j); } if (!bShouldSub) { bShouldSub = true; LOCK.notify(); if(i<49){ try { LOCK.wait(); } catch (InterruptedException e) { // TODO Auto-generatedcatch block e.printStackTrace(); } } } } } } }