今天有一个需求是:在一个方法中开启了一个子线程来执行操作,返回值依赖于子线程的执行结果,这样如果要返回正确的值,就需要开启子线程后
主线程等待子线程,然后子线程执行结束后,主线程再继续执行。
主线程等待子线程需要用到:CountDownLatch
代码如下:
importjava.util.concurrent.CountDownLatch;
publicclassCounter {
publicstaticintcount =0;
staticCountDownLatch cdl=newCountDownLatch(1000);//这里的数字,开启几个线程就写几
publicsynchronizedstaticvoidinc()throwsInterruptedException{//注意,如果不加上synchronized,由于并发写入,结果会小于1000
Thread.sleep(1);
count++;
cdl.countDown();
}
publicstaticvoidmain(String[] args)throwsInterruptedException{
for(inti =0; i <1000; i++){
newThread(newRunnable(){
publicvoidrun() {
// TODO Auto-generated method stub
try{
Counter.inc();
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
).start();
}
cdl.await();//主线程等待子线程执行输出
System.out.println(count);
}
}