Java ExecutorService Example – Tutorial(java线程池)

转自:http://examples.javacodegeeks.com/core-java/util/concurrent/executorservice/java-executorservice-example-tutorial/

另:http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors-and-threadpoolexecutor.html

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.

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.

 
 
 
 

1. Create the Runnable

We are going to create a Runnable that is intended to be executed by the ExecutorService. Create a java class named myThreadand paste the following code.

myThread.java:

01 package com.javacodegeeks.core.concurrency.executorservicetest;
02  
03 public class MyThread implements Runnable {
04      
05     private String myName;
06     private int count;
07     private final long timeSleep;
08  
09     MyThread(String name, int newcount, long newtimeSleep) {
10         this.myName = name;
11         this.count = newcount;
12         this.timeSleep = newtimeSleep;
13     }
14      
15     @Override
16     public void run() {
17         // TODO Auto-generated method stub
18  
19         int sum = 0;
20         for (int i = 1; i <= this.count; i++) {
21             sum = sum + i;
22         }
23         System.out.println(myName + " thread has sum = " + sum +
24                 " and is going to sleep for " + timeSleep);
25         try {
26             Thread.sleep(this.timeSleep);
27         catch (InterruptedException e) {
28             // TODO Auto-generated catch block
29             e.printStackTrace();
30         }
31     }
32  
33 }

The functionality of the Runnable is very simple. It computes a sum from the giving argument and it sleeps for a specified time.

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 eitherexecute() 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. CreateExecutorServiceTest.java file and paste the following.

ExecutorServiceTest.java:

01 package com.javacodegeeks.core.concurrency.executorservicetest;
02  
03 import java.util.concurrent.ExecutionException;
04 import java.util.concurrent.ExecutorService;
05 import java.util.concurrent.Executors;
06 import java.util.concurrent.Future;
07 import java.util.concurrent.TimeUnit;
08  
09 public class ExecutorServiceTest {
10  
11     private static Future taskTwo = null;
12     private static Future taskThree = null;
13      
14     public static void main(String[] args) throws InterruptedException, ExecutionException {
15         ExecutorService executor = Executors.newFixedThreadPool(2);
16         
17         // execute the Runnable
18         Runnable taskOne = new MyThread("TaskOne"2100);
19         executor.execute(taskOne);
20         for(int i = 0; i < 2; i++) {
21             // if this task is not created or is canceled or is completed
22             if ((taskTwo == null) || (taskTwo.isDone()) || (taskTwo.isCancelled())) {
23                 // submit a task and return a Future
24                 taskTwo = executor.submit(new MyThread("TaskTwo"4200));
25             }
26      
27             if ((taskThree == null) || (taskThree.isDone()) || (taskThree.isCancelled())) {
28                 taskThree = executor.submit(new MyThread("TaskThree"5100));
29             }
30             // if null the task has finished
31             if(taskTwo.get() == null) {
32                 System.out.println(i+1 ") TaskTwo terminated successfully");
33             else {
34                 // if it doesn't finished, cancel it
35                 taskTwo.cancel(true);
36             }
37             if(taskThree.get() == null) {
38                 System.out.println(i+1 ") TaskThree terminated successfully");
39             else {
40                 taskThree.cancel(true);
41             }
42         }
43         executor.shutdown();
44         System.out.println("-----------------------");
45         // wait until all tasks are finished
46         executor.awaitTermination(1, TimeUnit.SECONDS);
47         System.out.println("All tasks are finished!");
48      
49     }
50  
51 }

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值