在编写多线程代码时,如果主线程结束,那么子线程也会随之结束,如何等待线程结束再往下执行。
等待线程执行完成代码。
线程代码:
package demo;
import java.util.concurrent.CountDownLatch;
public class NodeSqlThread1 implements Runnable{
private CountDownLatch cdlSync;
public NodeSqlThread1(CountDownLatch cdlSync){
this.cdlSync=cdlSync;
}
@Override
public void run() {
for(int i=0;i<100;i++){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
cdlSync.countDown();
}
}
package demo;
import java.util.concurrent.CountDownLatch;
import com.hotent.BaseTestCase;
public class NodeSqlTest1 extends BaseTestCase {
static CountDownLatch cdlSync=new CountDownLatch(10);
@org.junit.Test
public void test() throws InterruptedException{
NodeSqlThread1 t =new NodeSqlThread1(cdlSync);
for(int i =0;i< 10;i++){
new Thread(t).start();
}
cdlSync.await();
System.out.println(cdlSync.getCount()+"完成");
}
}
最重要的是 cdlSync.await(); 它会等待所有线程结束后继续往下执行。