Java ExecutorService 예 -- 튜 토리 얼

6154 단어
Reference:https://examples.javacodegeeks.com/core-java/util/concurrent/executorservice/java-executorservice-example-tutorial/
ExecutorService is an interface that extends Executor class and represents an asynchronous execution. It provides us mechanisms to manage the end and detect progress of the asynchronous tasks.
Executor Service 는 Executor 를 계승 하 는 인터페이스 로 비동기 적 인 실행 을 대표 합 니 다.터미널 을 관리 하고 비동기 작업 수행 프로 세 스 를 발견 하 는 메커니즘 을 제공 합 니 다.
In this example we are going to see some basic functionalities of ExecutorService, as well as handle the Future object, the result of asynchronous computation.
이 예 에서 Executor Service 의 기본 기능 을 살 펴 보고 Future 대상 을 어떻게 처리 하 는 지, 비동기 실행 결과 등 을 알 아 보 자.
1. Runnable 대상 만 들 기
   We are going to create a Runnable that is intended to be executed by the ExecutorService. Create a java class named myThread and paste the following code.
   ExecutorService 에서 호출 할 수 있 도록 Runnable 인 터 페 이 스 를 만 듭 니 다.myThread 자바 클래스 를 만 듭 니 다:
package com.javacodegeeks.core.concurrency.executorservicetest;

public class MyThread implements Runnable {
	
	private String myName;
	private int count;
	private final long timeSleep;

	MyThread(String name, int newcount, long newtimeSleep) {
		this.myName = name;
	    this.count = newcount;
	    this.timeSleep = newtimeSleep;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub

		int sum = 0;
	    for (int i = 1; i <= this.count; i++) {
	    	sum = sum + i;
	    }
	    System.out.println(myName + " thread has sum = " + sum + 
	    		" and is going to sleep for " + timeSleep);
	    try {
			Thread.sleep(this.timeSleep);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 이 Runnable 의 기능 은 매우 간단 합 니 다. 주어진 매개 변수의 합 을 계산 하고 이 기간 동안 휴면 합 니 다.
2. Code the ExecutorService In this example we will use a factor method of ExecutorService that creates a thread pool of fixed number of threads. For this reason, newFixedThreadPool() method is used where we specify the number of threads in the pool. To execute the thread, we can use either execute() method or submit(), where both of them take Runnable as a parameter. execute() method is depending on the implementation of the Executor class and may perform the Runnable in a new thread, in a pooled thread, or in the calling thread. submit() method extends execute(), by returning a Future that represents the submitting task.
The Future can be used to indicate the termination of execution of the thread. For instance, get() method waits for the completion of the computation. If the returning value is null, the task has finished correctly. Otherwise, cancel() method can be called in order to end the execution of this task. It is worth to mention that for bulk or a collection of thread execution, invokeAll() and invokeAny() are used respectively, although there are not used in this example.
To close down the ExecutorService, there are many methods that can be used. In our example we use shutdown() method, in which the submitted tasks are executed before the shutting down but new tasks can not be accepted. Another approach is shutdownNow() method, which stops the executing tasks, pause the waiting ones and returns the list of the awaiting ones. Moreover, awaitTermination() can be used in order to wait until all threads are terminated.
For further understanding of the main functionality of ExecutorService, have a look at the code below. Create ExecutorServiceTest.java file and paste the following. ExecutorServiceTest.java:
package com.javacodegeeks.core.concurrency.executorservicetest;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceTest {

	private static Future taskTwo = null;
	private static Future taskThree = null;
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService executor = Executors.newFixedThreadPool(2);
	   
		// execute the Runnable
	    Runnable taskOne = new MyThread("TaskOne", 2, 100);
	    executor.execute(taskOne);
	    for(int i = 0; i < 2; i++) {
	    	// if this task is not created or is canceled or is completed
			if ((taskTwo == null) || (taskTwo.isDone()) || (taskTwo.isCancelled())) {
				// submit a task and return a Future
				taskTwo = executor.submit(new MyThread("TaskTwo", 4, 200));
			}
	
			if ((taskThree == null) || (taskThree.isDone()) || (taskThree.isCancelled())) {
				taskThree = executor.submit(new MyThread("TaskThree", 5, 100));
			}
			// if null the task has finished
			if(taskTwo.get() == null) {
				System.out.println(i+1 + ") TaskTwo terminated successfully");
			} else {
				// if it doesn't finished, cancel it
				taskTwo.cancel(true);
			}
			if(taskThree.get() == null) {
				System.out.println(i+1 + ") TaskThree terminated successfully");
			} else {
				taskThree.cancel(true);
			}
	    }
	    executor.shutdown();
	    System.out.println("-----------------------");
	    // wait until all tasks are finished
	    executor.awaitTermination(1, TimeUnit.SECONDS);
	    System.out.println("All tasks are finished!");
	
	}

}

Now you can see the output of the execution.
Output:
TaskOne thread has sum = 3 and is going to sleep for 100
TaskTwo thread has sum = 10 and is going to sleep for 200
TaskThree thread has sum = 15 and is going to sleep for 100
1) TaskTwo terminated successfully
1) TaskThree terminated successfully
TaskTwo thread has sum = 10 and is going to sleep for 200
TaskThree thread has sum = 15 and is going to sleep for 100
2) TaskTwo terminated successfully
2) TaskThree terminated successfully
-----------------------
All tasks are finished!
Download the source code

This was an example of ExecutorService in Java. Download the source code of this example: ExecutorServiceTest.zip

좋은 웹페이지 즐겨찾기