求大神幫忙:啟動3個線程打印遞增的數字, 線程1先打印1,2,3,4,5, 然后是線程2打印6,7,8,9,10, 然后是線程3打印11,12,13,14,15. 接着再由線程1打印16,17,18,19,20....以此類推, 直到打印到75.


package com.unit10.HomeWork;

public class HomeWork003 {


/**
* 創建三個線程進行分段疊加
* 每個線程疊加四次
*
*/

public static void main(String[] args) {
new Thread(new Add(1)).start();
new Thread(new Add(2)).start();
new Thread(new Add(3)).start();
}
}
class Add implements Runnable{
//定義一個線程ID
private int threadID;
//需要進行疊加的數字
private static int printNum = 0;
//構造方法獲取thread的ID
public Add(int threadID){
this.threadID = threadID;
}
@Override
public void run() {
//需要疊加的數字小於75繼續疊加
while (printNum < 75){
//Add.class表示 Add 對象 = new Add();
//Add.class表示Add類的一個不確定對象
synchronized (Add.class){
System.out.println("當前的線程是:"+"---->"+threadID+"線程");
int index = (printNum/5%3+1);
System.out.println("當前的數字是:"+"---->"+printNum);
System.out.println("當前的指針是:"+"---->"+index);
//線程ID和指針相同時可以進入疊加for循環
if(index == threadID){
for ( int i = 0 ; i < 5 ; i++){
System.out.println("線程"+threadID+":"+(++printNum));
}
//執行完畢,喚醒其他線程
Add.class.notify();
}else {
System.out.println("我去換個線程!");
try {
Add.class.wait();
//該線程不和條件,進行等待其他線程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM