Java并发 专题
您的位置:java > Java并发专题 > Java并发Executor接口
Java并发Executor接口
作者:--    发布时间:2019-11-20

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

executor接口中的方法

序号 方法 描述
1 void execute(runnable command) 在将来的某个时间执行给定的命令。

实例

以下testthread程序显示了如何在基于线程的环境中executor接口的用法。

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();
         }
      }
   }
}

执行上面代码,得到如下结果 -

running task!
task completed

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册