父线程等候10个子线程完成的例子

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

这是个挺有趣的程序,我写了个例子同步了10个子线程,可以参考下:

public class Test {

static Test test = null;

static int childNum = 0;

synchronized static void decSem(){

childNum--;

if(childNum == 0){

synchronized(test){

test.notify();

}

}

}

Test(){

test = this;

}

void connectDB() throws InterruptedException{

synchronized(this){

childNum = 10;

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

new TestThread().start();

wait();

}

}

public static void main(String[] args) throws InterruptedException {

System.out.println("Start...");

Test test = new Test();

test.connectDB();

System.out.println("End.");

}

}

class TestThread extends Thread{

public void run() {

super.run();

System.out.println("child thread");

Test.decSem();

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航