2012년 8월 1일 수요일

안드로이드 스레등 3/10

3편이다. 동료 광현츼를 위해서 좀 더 적어 본다. ㅋㅋ

자바 1.5부터 추가된 기능인..


욤마 요거 ...

쓰는 법은 간단하다.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HelloWorld {

private volatile static int a = 0;
public HelloWorld() {
Runnable r = new IamFine("first");
Runnable rr = new IamFine("second");
// Thread t1 = new Thread(r);
// Thread t2 = new Thread(rr);
//
// try {
// t1.start();
// t2.start();
// } catch (Exception e) {
// // TODO: handle exception
// }
ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(r);
        executorService.execute(rr);
        executorService.shutdown();

}
class IamFine implements Runnable {
String name;
public IamFine (String name) {
this.name = name;
}
public void run() {
while (true) {
// synchronized(java.lang.Object.class) {
a += 1;
System.out.println(name + "'s Current Count = " + a);
// }
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
System.out.println("Hello World.");
new HelloWorld();
}
}

요렇게 쓴다.

Thread 를 써서 new 해주는 대신에   ExecutorService executorService = Executors.newFixedThreadPool(2);
를 생성해서

  executorService.execute(r);
         executorService.execute(rr);
         executorService.shutdown();

요렇게 쓰면 된다.

뭐 사실 별반 차이 없어 보인다. 멀티 쓰레드 관리를 잘 해 준다고 하는데 도대체 뭘 잘해주는 건지 파보지 않고서는 약장수  말을 믿을 수 밖에... 그러나 synconized 구문의 주석을 풀어주면 확실히 경쟁 상태 없이 제대로 동작함을 볼 수 있다.
역시 java.lang.Object.class는 소중함.


newFixedThreadPool(2)에서 2는 쓰레드 개수를 적어 주면 된다.

shutdown하면 멈출 것 같은데 새로운 작업 추가를 안되게 하는 것이고 대기중인 작업은 실행이 된다.

위 예제에서 무한루프에 중간중간 sleep 으로 대기를 하는거니까 계속 실행되는데 아무런 지장이 없다.(사실 애초부터 계속 실행되는게 문제였다 ㅋㅋ)

암튼 이런 기능도 있응께.

안드로이드에서 금방 끝나는 작업이고 한꺼번에 뭐 많이 해야 하면 한번 써봄직하다.
(한꺼번에 해도 금방 끝나는 작업이어야 할것이다)


위에 말한 링크에 있는 공식 Example 긁어 뿌리면서 마무리 해 본다.


Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:
 class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }

 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }
 
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

댓글 없음:

댓글 쓰기

국정원의 댓글 공작을 지탄합니다.

UPBIT is a South Korean company, and people died of suicide cause of coin investment.

 UPBIT is a South Korean company, and people died of suicide cause of coin. The company helps the people who control the market price manipu...