如何实现主线程需要等待子线程的结果,然后才能往下执行。
1. 使用FLAG标志位
[java] view plaincopy
public class TestSync {
private static int FLAG = 0;
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
System.out.println("thread 1 is start");
thread1.start();
while (FLAG != 1) {
// System.out.println("main thread is waiting");
}
FLAG = 0;
System.out.println("main thread is back to work");
}
static class Thread1 extends Thread {
int total;
public void run() {
System.out.println("thread 1 is running");
for (int i = 0; i < 5; i++) {
total = total + i;
System.out.println("total = " + total);
}
System.out.println("thread 1 is over and set flag to 1");
FLAG = 1;
}
}
}
PS: 在这个期间,做一些跟thread1不相关的事情 还是可以的哦
[java] view plaincopy
while (FLAG != 1) {
// System.out.println("main thread is waiting");
}
[java] view plaincopy
输出结果:
2.join(),理解成等待子线程终止,可用于等待一个或多个子线程的结果,然后主线程再继续执行。
[java] view plaincopy
public class TestSync {
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<5 ;i++){
Thread1 thread1 = new Thread1();
System.out.println("thread " + i +" is start");
thread1.start();
thread1.join();
}
System.out.println("main thread is back to work");
}
static class Thread1 extends Thread {
public void run() {
System.out.println("thread is running");
}
}
}
输出结果:
3. CountDownLatch 这个原理应该是通过检查子线程的个数来实现的
[java] view plaincopy
import java.util.concurrent.CountDownLatch;
public class TestSync {
private static CountDownLatch countdownLatch = new CountDownLatch(5);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 5; i++) {
Thread1 thread1 = new Thread1();
System.out.println("thread " + i + " is start");
thread1.start();
}
//用于等待
countdownLatch.await();
System.out.println("main thread is back to work");
}
static class Thread1 extends Thread {
public void run() {
System.out.println("thread is running");
//执行完一个用于减少子线程计数的
countdownLatch.countDown();
}
}
}
输出结果:
PS: 通过输出结果发现,join()的话,貌似子线程们是串行执行的啊。。。会影响效率的吧。。。