Java 获取多线程返回值的几种方式
第一种:使用Callable加上FutureTask来实现
public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Integer> futureTask=new FutureTask(new TestA()); Thread thread=new Thread(futureTask); thread.start(); Integer integer = futureTask.get(); System.out.println(integer); } static class TestA implements Callable<Object>{ @Override public Integer call() throws Exception { Thread.sleep(1000); return 1; } }
Callable的call方法已经规定线程的返回值了,很好理解 第二种:主线程等待,直到子线程执行完成
public static void main(String[] args) throws InterruptedException { ThreadTest threadTest=new ThreadTest(); threadTest.start(); while (threadTest.a==null){ Thread.sleep(100); } System.out.println(threadTest.a); } static class ThreadTest extends Thread{ Integer a; @Override public void run() { super.run(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } a=1; } }
第三种:与第二种类似采用Thread的join方法,主线程会等调用了join的子线程执行完后再执行
public static void main(String[] args) throws InterruptedException { ThreadTest threadTest=new ThreadTest(); threadTest.start(); threadTest.join(); System.out.println(threadTest.a); } static class ThreadTest extends Thread{ Integer a; @Override public void run() { super.run(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } a=1; } }
第四种:使用CountDownLatch,CountDownLatch的await方法表示等待,countDown方法表示等待线程数减一,当等待线程数为0时,开始向下执行
public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch=new CountDownLatch(1); ThreadTest02 threadTest02=new ThreadTest02(countDownLatch); threadTest02.start(); countDownLatch.await(); System.out.println(threadTest02.a); } static class ThreadTest02 extends Thread{ private CountDownLatch countDownLatch; private int a; public ThreadTest02(CountDownLatch countDownLatch){ this.countDownLatch=countDownLatch; } @Override public void run() { super.run(); try { Thread.sleep(1000); a=1; } catch (InterruptedException e) { e.printStackTrace(); } countDownLatch.countDown(); } }