Javaスレッド通信(一)

5672 ワード

スレッド間でどのように通信すべきかを例によって分析します.
タイトル:
サブスレッドを10回、メインスレッドを100回、サブスレッドを10回、メインスレッドを50回、プログラムを書き出してください.
まずこのテーマを分析する
サブスレッドループ10回プライマリスレッドループ100回これはビジネスメソッドであり,オブジェクト向けの考え方「高集約」に基づいてこの2つのビジネスメソッドを1つのクラスにカプセル化すべきである.
//Busindessビジネスメソッドクラスにカプセル化(高集約)subとmainメソッドの反発
class Businness{ public synchronized void sub(int index){ for(int i=0;i<10;i++){ System.out.println("...sub running..."+i +"loop of "+index); } } public synchronized void main(int index){ for(int i=0;i<10;i++){ System.out.println("...main running..."+i +"loop of "+index); } } }
main(){
final Businness b = new Businness(); new Thread(new Runnable() { public void run() { for(int i=0;i<10;i++) b.sub(i+1); } }).start(); for(int i=0;i<20;i++){ b.main(i+1); }
}
このとき2つの方法は異なるスレッドアクセス時に反発しただけで通信はありません...
2つのスレッドはどのように通信しますか?
Objectクラスのwait()[待機...]notify() notifyAll()【 】 JDK wait() ...
synchronized (obj) {
 while (<condition does not hold>)
 obj.wait();
 ... // Perform action appropriate to condition
}
JDK wait    

throw java.lang.IllegalMonitorStateException  Business class Businness{
//
private boolean subStart = true;
// this
public synchronized void sub(int index){
while(!subStart){// subStart=false ...
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0;i<10;i++){
System.out.println("...sub running..."+(i+1) +"loop of "+index);
}
subStart = false;
this.notify();
}
public synchronized void main(int index){

while(subStart){//subStart=true
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

for(int i=0;i<100;i++){
System.out.println("...main running..."+(i+1) +"loop of "+index);
}
subStart = true;
this.notify();
}
}

main (){ final Businness b = new Businness(); //
new Thread(new Runnable() {
public void run() {
for(int i=0;i<50;i++)
b.sub(i+1);
}
}).start();
//main
for(int i=0;i<50;i++){
b.main(i+1);
}
}
Business sub main ...