1. 程式人生 > >2、主執行緒子執行緒輪流執行執行緒管理實現

2、主執行緒子執行緒輪流執行執行緒管理實現

程式設計題目:

2.子執行緒迴圈10次,接著主執行緒迴圈5次,接著又回到子執行緒迴圈10次,接著再回到主執行緒又迴圈5次,如此迴圈50次,請寫出程式。

示例程式碼:

package program.thread.exercise02;

/**
 * 2.子執行緒迴圈10次,接著主執行緒迴圈5次,接著又回到子執行緒迴圈10次,接著再回到主執行緒又迴圈5次,如此迴圈50次,請寫出程式。 
 */

public class ThreadManager {
    public static void main(String[] args) {

        Business business = new
Business();//建立例項物件 new Thread( new Runnable(){ public void run() { for(int i=0;i<50;i++){//總迴圈次數 business.subThread(i); business.mainThread(i); } } } ).start(); } } //建立事務類
class Business { //定義執行緒執行:true為子執行緒執行,false為主執行緒執行 boolean should = true;//這裡相當於定義了控制該誰執行的一個訊號燈 //主執行緒,注意:主執行緒和子執行緒要同步 public synchronized void mainThread(int i){ if(should){ try { this.wait();//主執行緒處在等待狀態 } catch (InterruptedException e) { e.printStackTrace(); } } for
(int j=0;j<5;j++){ //主執行緒執行次數 System.out.println("主執行緒:i="+i+",j="+j); } should = true; this.notify();//喚醒主執行緒 } //子執行緒 public synchronized void subThread(int i){ if(!should){ try { this.wait();//子執行緒處在等待狀態 } catch (InterruptedException e) { e.printStackTrace(); } } for(int j=0;j<10;j++){ //子執行緒執行次數 System.out.println("子執行緒:i="+i+",j="+j); } should = false; this.notify();//喚醒子執行緒 } }

結果顯示:

這裡寫圖片描述