`

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

阅读更多
一、如何使用 ExecutorService.submit() ?

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


二、程序


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系列文章

00_Java之 java.util.concurrent 包之概述

01_Java之java.util.concurrent包之Executor与ExecutorService

02_Java之 java.util.concurrent 包之ExecutorService之submit () 之 Future

03_Java之多线程之Callable与Future

04_Java之多线程之Lock





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











-
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics