Java Concurrency 简明教程

Java Concurrency - Executor Interface

java.util.concurrent.Executor 接口是一个支持启动新任务的简单接口。

A java.util.concurrent.Executor interface is a simple interface to support launching new tasks.

ExecutorService Methods

Sr.No.

Method & Description

1

void execute(Runnable command) Executes the given command at some time in the future.

Example

以下 TestThread 程序展示了在基于线程的环境中使用 Executor 接口。

The following TestThread program shows usage of Executor interface in thread based environment.

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      Executor executor = Executors.newCachedThreadPool();
      executor.execute(new Task());
      ThreadPoolExecutor pool = (ThreadPoolExecutor)executor;
      pool.shutdown();
   }

   static class Task implements Runnable {

      public void run() {

         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed");
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

这将产生以下结果。

This will produce the following result.

Output

Running Task!
Task Completed