您的位置:首页 > 职场人生

java面试题:如何让三个子线程执行完,再执行主线程

2017-07-30 15:43 357 查看
让三个子线程执行完再执行主线程的三种实现方式

方法一:利用CountDownLatch类

public class CountDownLatchTest {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(10);
LatchDemo ld = new LatchDemo(latch);
for (int i = 0; i < 10; i++) {
new Thread(ld).start();
}

try {
latch.await();//让主线程等待多个执行完后(即latch变为)再执行
} catch (InterruptedException e) {
}
System.out.println("主线程执行" );
}

}

class LatchDemo implements Runnable {
//多线程需共享latch
private CountDownLatch latch;
public LatchDemo(CountDownLatch latch) {
this.latch = latch;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行结束");
latch.countDown();
}

}


方法二:利用join方法
public class JoinTest {
public static void main(String[] args) {
ThreadDemoJ td = new ThreadDemoJ();
try {
Thread thread1 = new Thread(td);
Thread thread2 = new Thread(td);
Thread thread3 = new Thread(td);
thread1.start();
thread2.start();
thread3.start();
//让三个线程执行完,如果在调用start方法后面直接调用join方法,那么三个线程将串行
thread1.join();
thread2.join();
thread3.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("主线程结束执行");
}

}

class ThreadDemoJ implements Runnable{
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"执行");
} catch (Exception e) {
e.printStackTrace();
}
}
}

注意:
join():等待该线程结束,后面的语句一定会等待该线程结束才执行,该方法有三个有两个有参的重载方法
join(long millis):等待该线程millis
毫秒,不管该线程是否执行结束,后面的语句都开始执行
join(long millis, int nanos):等待该线程millis+nanos
毫秒,不管该线程是否执行结束,后面的语句都开始执行
后面两个方法是不一定等待该线程执行完的。

方法三:利用Callable接口和FutureTask类
public class CallableTest {
public static void main(String[] args) {
ThreadDemoCa td = new ThreadDemoCa();

//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask<Integer> result1 = new FutureTask<>(td);
FutureTask<Integer> result2 = new FutureTask<>(td);
FutureTask<Integer> result3 = new FutureTask<>(td);

new Thread(result1).start();
new Thread(result2).start();
new Thread(result3).start();
try {
result1.get();
result2.get();
result3.get();
//2.接收所有线程运算后主线程才执行
System.out.println("主线程执行");
} catch (Exception e) {
e.printStackTrace();
}
}

}

class ThreadDemoCa implements Callable<Integer>{

//需要实现call()方法
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+"执行结束");
return 1;
}

}


博主为新手,如有不对请指出,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题 线程