要求::
等待下一个线程的执行,直到上一个完成 . 无论时间消耗如何,下一个线程都必须在前一个线程停止之前才能启动 . 它必须简单易用 .
答案::
@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并发 .