자바 의 java.util.concurrent 패키지 의 ExecutorService submit()의 Future

더 읽 기
1.Executor Service.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{  
    @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 패키지 의 Executor 시리즈 글
00_자바 의 java.util.concurrent 패키지 개요
01_자바 의 자바.util.concurrent 패키지 의 Executor 와 ExecutorService
02_자바 의 java.util.concurrent 패키지 의 ExecutorService submit()의 Future
03_자바 의 다 중 스 레 드 Callable 과 Future
04_자바 의 다 중 스 레 드 Lock
전재 하 다.
원문의 출처:http://lixh1986.iteye.com/blog/2360306
-

좋은 웹페이지 즐겨찾기