Java之 java.util.concurrent 包之ExecutorService之submit () 之 Future

本文详细介绍了Java中ExecutorService接口的使用方法,包括submit()方法的参数传递、Future对象的作用及获取任务结果的方式。同时对比了Callable与Runnable的区别,并通过实例演示了如何关闭线程池。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=medium][b]一、如何使用 ExecutorService.submit() ?[/b][/size]

[b]submit() [/b]
可以接受 Callable 或 Runnable 对象。
返回值是 Future 对象(调用 Future 对象的 get() 方法会导致主线程阻塞)。


[size=medium][b]二、程序[/b][/size]



import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

public class TestExecutorService {

class Runnabled implements Runnable{
@Override
public void run() {
System.out.println("[Runnable-child] running...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Callabled implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("[Callable-child] calling...");
Thread.sleep(100);
return "finished";
}
}
//==========================================================

@Test
public void test() throws Exception{
testExecutorService_Runnable();
testExecutorService_Callable();
testExecutorService_shutdown();
}

//==========================================================
public void testExecutorService_Runnable() throws Exception {

Runnabled runnable = new Runnabled();
ExecutorService es1 = Executors.newCachedThreadPool();

for(int i = 0; i < 10; i++){
System.out.println("[Runnable] main thread : " + i + "[Blocked in Main]");
es1.submit(runnable).get();
}

for(int i = 0; i < 10; i++){
System.out.println("[Runnable] main thread : " + i);
es1.execute(runnable);
//es1.submit(runnable) // same as, if you don't expect a result.
}
}

public void testExecutorService_Callable() throws Exception{

ExecutorService es2 = Executors.newScheduledThreadPool(10);
Callabled callable = new Callabled();

for(int i = 0; i < 10; i++){
System.out.println("[Callable] main thread : " + i + "[Blocked in Main]");
es2.submit(callable).get();
}

for(int i = 0; i < 10; i++){
System.out.println("[Callable] main thread : " + i);
es2.submit(callable);
}
}

public void testExecutorService_shutdown() throws Exception{

ExecutorService es2 = Executors.newScheduledThreadPool(10);

/*
Does not wait for previously submitted tasks to complete execution.
Start an immediately shutdown and no new tasks will be accepted.

The invocation has no additional effect if already shut down.
*/
es2.shutdown();


/*
Blocks, until all tasks have completed execution after
1) a shutdown request,
2) or the timeout occurs,
3) or the current thread is interrupted,
whichever happens first.
*/
es2.awaitTermination(10000, TimeUnit.SECONDS);

System.out.println("----------------------------");
System.out.println("print me immediately after all task completed.");
System.out.println("no need to wait for 10000 seconds.");


}





/**
NOTE: ExecutorService.shutdown()
VS
ExecutorService.awaitTermination()

1.
awaitTermination() will wait for all task to complete.
shutdown() method does not wait.

if shutdown() method comes before awaitTermination(),
Then when all task complete in or less than timeout,
thread will shut down immediately.

2.
If you want to get the task result immediately, you should
use:
result = exec.submit(Callable/Runnable).get();
NOTE:
If you call get(), it will be blocked.
If you just call submit(), it will not be blocked.

3.
If you want to get the task result after all task completed,
you can store the Future object in to a collection.
use:

Future f = exec.submit(Callable/Runnable);
arrayList.add(f);

then after all task completed, you can retrieve the Future
objects stored in arrayList.

*/


/**
* NOTE: Callable VS Runnable
*
* Callable and Runnable are almost same when using
* ExecutorService.submit() method.
*
* They can be both blocked when using Future.get()
* method.
*
* while:
* 1. Callable's call() method can return a result.
* Runnable's run() method is void.
*
* 2. Callable's call() method throws exception.
* Runnable's run() method cannot throw exception.
*/

}




/*
Result:
===============================================================

[Runnable] main thread : 0 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 1 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 2 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 3 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 4 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 5 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 6 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 7 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 8 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 9 [Blocked in Main]
[Runnable-child] running...

[Runnable] main thread : 0
[Runnable] main thread : 1
[Runnable-child] running...
[Runnable-child] running...
[Runnable] main thread : 2
[Runnable] main thread : 3
[Runnable-child] running...
[Runnable] main thread : 4
[Runnable-child] running...
[Runnable] main thread : 5
[Runnable-child] running...
[Runnable] main thread : 6
[Runnable-child] running...
[Runnable] main thread : 7
[Runnable-child] running...
[Runnable] main thread : 8
[Runnable-child] running...
[Runnable] main thread : 9
[Runnable-child] running...
[Runnable-child] running...


[Callable] main thread : 0 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 1 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 2 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 3 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 4 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 5 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 6 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 7 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 8 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread : 9 [Blocked in Main]
[Callable-child] calling...

[Callable] main thread : 0
[Callable] main thread : 1
[Callable] main thread : 2
[Callable-child] calling...
[Callable] main thread : 3
[Callable-child] calling...
[Callable-child] calling...
[Callable-child] calling...
[Callable] main thread : 4
[Callable] main thread : 5
[Callable-child] calling...
[Callable-child] calling...
[Callable] main thread : 6
[Callable] main thread : 7
[Callable-child] calling...
[Callable-child] calling...
[Callable] main thread : 8
[Callable] main thread : 9
[Callable-child] calling...
[Callable-child] calling...

----------------------------
print me immediately after all task completed.
no need to wait for 10000 seconds.

*/




java.util.concurrent包之Execuotor系列文章

[url=http://lixh1986.iteye.com/blog/2341898]00_Java之 java.util.concurrent 包之概述[/url]

[url=http://lixh1986.iteye.com/blog/2360304]01_Java之java.util.concurrent包之Executor与ExecutorService[/url]

[url=http://lixh1986.iteye.com/blog/2360306]02_Java之 java.util.concurrent 包之ExecutorService之submit () 之 Future[/url]

[url=http://lixh1986.iteye.com/blog/2351367]03_Java之多线程之Callable与Future[/url]

[url=http://lixh1986.iteye.com/blog/2351294]04_Java之多线程之Lock[/url]


转载请注明,
原文出处:http://lixh1986.iteye.com/blog/2360306


-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值