java futher多线程_如何让Java线程等待另一个线程的输出?

要求::

等待下一个线程的执行,直到上一个完成 . 无论时间消耗如何,下一个线程都必须在前一个线程停止之前才能启动 . 它必须简单易用 .

答案::

@See java.util.concurrent.Future.get()doc . future.get()等待计算完成所需,然后检索其结果 .

任务完成!!见下面的例子

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import org.junit.Test;

public class ThreadTest {

public void print(String m) {

System.out.println(m);

}

public class One implements Callable {

public Integer call() throws Exception {

print("One...");

Thread.sleep(6000);

print("One!!");

return 100;

}

}

public class Two implements Callable {

public String call() throws Exception {

print("Two...");

Thread.sleep(1000);

print("Two!!");

return "Done";

}

}

public class Three implements Callable {

public Boolean call() throws Exception {

print("Three...");

Thread.sleep(2000);

print("Three!!");

return true;

}

}

/**

* @See java.util.concurrent.Future.get() doc

*

* Waits if necessary for the computation to complete, and then

* retrieves its result.

*/

@Test

public void poolRun() throws InterruptedException, ExecutionException {

int n = 3;

// Build a fixed number of thread pool

ExecutorService pool = Executors.newFixedThreadPool(n);

// Wait until One finishes it's task.

pool.submit(new One()).get();

// Wait until Two finishes it's task.

pool.submit(new Two()).get();

// Wait until Three finishes it's task.

pool.submit(new Three()).get();

pool.shutdown();

}

}

该程序的输出::

One...

One!!

Two...

Two!!

Three...

Three!!

您可以看到在完成任务之前需要6秒,这比其他线程更大 . 所以Future.get()等待任务完成 .

如果你不使用future.get(),它不会等待完成并执行基于时间的消耗 .

祝你好运与Java并发 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值