線程學(xué)習(xí)筆記【4】---線程之間通信
子線程先循環(huán)10次,然后主線程循環(huán)100次,再子線程循環(huán)10次,主線程循環(huán)100次,就這樣循環(huán)往復(fù)50次。
public class Communtion01 {
public static void main(String args[]) {
final Bussiness buss = new Bussiness();
new Thread(new Runnable() {
public void run() {
for (int j = 1; j <= 50; j++) {
buss.sub(j);
}
}
}).start();
for (int j = 1; j <= 50; j++) {
buss.main(j);
}
}
}
class Bussiness {
private boolean subFlag = true;
//Cpu照顧sub線程,執(zhí)行到sub(),但還不該sub執(zhí)行,那就wait
public synchronized void sub(int j) {
while (!subFlag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "在第" + j
+ "次循環(huán)了" + i);
}
subFlag = false;
this.notify();
}
public synchronized void main(int j) {
while(subFlag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i =1; i <=100; i++) {
System.out.println(Thread.currentThread().getName() + "在第" + j
+ "次循環(huán)了" + i);
}
subFlag = true;
this.notify();
}
}
經(jīng)驗(yàn):要用到共同數(shù)據(jù)(包括同步鎖)或共同算法的若干方法應(yīng)該歸在同一個(gè)類身上,這種設(shè)計(jì)體現(xiàn)了高類聚和程序的健壯性。
互斥、同步、通信問題的邏輯不是寫在線程代碼上,而是在線程訪問那個(gè)資源類上。
posted on 2011-08-29 17:31 日出星辰 閱讀(85) 評(píng)論(0) 編輯 收藏