Java并发编程之线程管理(Executor框架16)

来源:互联网 发布:女网络歌手2016 编辑:程序博客网 时间:2024/06/06 01:19

4.6 在一个执行器中删除一个任务

    当你使用Executor时,你没有必要管理线程,因为它已经帮我们管理了线程。你仅仅需要实现Runnable或者Callable任务并发送它们给这个执行器executor。这个executor负责在线程池中创建、管理线程,并且如果它们不需要了,直接结束这些线程。有时,你可能想去删除一个你已经发送给executor的任务。这种情况,你直接调用Future对象的cancel()方法就可以了,它实现就得就是删除操作。请看下面的这个实例。

   

 importjava.util.concurrent.Callable;import java.util.concurrent.Executors;import java.util.concurrent.Future;importjava.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit; public class Task implements Callable<String>{     /**     * Main method of the task. It has an infiniteloop that writes a message to     * the console every 100 milliseconds     */    @Override    public String call() throws Exception {        while (true){            System.out.printf("Task: Test\n");            Thread.sleep(100);        }    }    /**     * @param args     */    public staticvoidmain(String[] args) {        // Create an executor                ThreadPoolExecutorexecutor=(ThreadPoolExecutor)Executors.newCachedThreadPool();                               // Create a task                Task task=new Task();                               System.out.printf("Main: Executing the Task\n");                 // Send the task to the executor                Future<String>result=executor.submit(task);                               // Sleep during two seconds                try {                    TimeUnit.SECONDS.sleep(2);                } catch (InterruptedException e) {                    e.printStackTrace();                }                               // Cancel the task, finishing its execution                System.out.printf("Main: Cancelling the Task\n");                result.cancel(true);                // Verify that the task has been cancelled                System.out.printf("Main: Cancelled: %s\n",result.isCancelled());                System.out.printf("Main: Done: %s\n",result.isDone());                               // Shutdown the executor                executor.shutdown();                System.out.printf("Main: The executor has finished\n");        }  }

运行结果:

Main:Executing the TaskTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestTask:TestMain:Cancelling the TaskMain:Cancelled: trueMain:Done: trueMain: The executor has finished


0 0
原创粉丝点击