主线程等待其他线程执行结束的几种方式
1.yield
主线程通过 Thread.activeCount()>1 方式判断子线程是否结束运行。
class MyThread extends Thread {
@Override
public void run() {
try {
sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class UseExecutors {
public static void main(String[] args) {
try {
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.execute(new MyThread());
pool.shutdown();
System.out.println("main end...");
while(Thread.activeCount()>1){ //保证前面的线程都执行完
System.out.println(Thread.activeCount());
Thread.yield();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
System.out.println("finally...");
System.exit(0);
}
}
}
2.AtomicInteger
class MyThread2 extends Thread {
@Override
public void run() {
try {
MainThreadWait_AtomicInteger.runThreadCount.incrementAndGet();
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
MainThreadWait_AtomicInteger.runThreadCount.decrementAndGet();
}
}
}
public class MainThreadWait_AtomicInteger {
public static AtomicInteger runThreadCount = new AtomicInteger(0);
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.execute(new MyThread2());
pool.execute(new MyThread2());
pool.execute(new MyThread2());
pool.shutdown();
while(true){
if(runThreadCount.get()==0){
System.out.println("other thread end...");
break;
}
}
System.out.println("main end...");
}
}
3.CountDownLatch
class MyThread3 extends Thread {
CountDownLatch countDownLatch;
public MyThread3(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
countDownLatch.countDown();
}
}
}
public class MainThreadWait_CountDownLatch {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.execute(new MyThread3(countDownLatch));
pool.execute(new MyThread3(countDownLatch));
pool.execute(new MyThread3(countDownLatch));
pool.shutdown();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main end...");
}
}
4.join.
5.future.
...
浙公网安备 33010602011771号