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();
}
}
}
}
}
}