Java多線程經典案例
/**
* 典型案例:子線程執行10次,主線程執行100次,兩者交替50次。
*/
package cn.itcast.lesson4;
public class TestWaitNotify {
public static void main(String[] args){
final Business business= new Business();
new Thread(
new Runnable() {
public void run() {
for(int i=1;i<=50;i++){
business.sub(i);
}
}
}
).start();
for(int i=1;i<=50;i++){
business.main(i);
}
}
}
class Business{
private boolean bShouldSub = true;
public synchronized void sub(int i){
//如果bussiness調用sub的話,則【!bShouldSub =false,bShouldSub=true】;
//然後主線程main為等待,執行完sub後就bShouldSub=false;喚醒主線程main。
while(!bShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread sequence of "+j+",loop of "+i);
}
bShouldSub = false;
//喚醒main
this.notify();
}
public synchronized void main(int i){
while(bShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread sequence of "+j+",loop of "+i);
}
bShouldSub = true;
//喚醒sub
this.notify();
}
}
Java1.5後的多線程框架 http://www.linuxidc.com/Linux/2014-02/96879.htm
Java多線程和同步的理解 http://www.linuxidc.com/Linux/2013-12/93691.htm
Java中兩種實現多線程方式的對比分析 http://www.linuxidc.com/Linux/2013-12/93690.htm
Java利用多線程計算目錄數據大小 http://www.linuxidc.com/Linux/2013-09/90715.htm
Java多線程向數據庫寫入數據 http://www.linuxidc.com/Linux/2013-09/90297.htm