标签:nts Fix exec 有一个 另一个 [] max 服务器 传递
合理利用线程池能够带来三个好处。
[x] public static ExecutorService newCachedThreadPool()
[x] public static ExecutorService newSingleThreadExecutor()
[x] public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
实例代码
Executor 执行 Runnable 任务
通过 Executors 的以上四个静态工厂方法获得 ExecutorService 实例,而后调用该实例的 execute(Runnable command)方法即可。
一旦 Runnable 任务传递到 execute()方法,该方法便会自动在一个线程上执行。
下面是 Executor 执行 Runnable 任务的示例代码:
1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 4 public class TestCachedThreadPool{ 5 public static void main(String[] args){ 6 ExecutorService executorService = Executors.newCachedThreadPool(); 7 // ExecutorService executorService = Executors.newFixedThreadPool(5); 8 // ExecutorService executorService = Executors.newSingleThreadExecutor(); 9 for (int i = 0; i < 5; i++){ 10 executorService.execute(new TestRunnable()); 11 System.out.println("************* a" + i + " *************"); 12 } 13 executorService.shutdown(); 14 } 15 } 16 17 class TestRunnable implements Runnable{ 18 public void run(){ 19 System.out.println(Thread.currentThread().getName() + "线程被调用了。"); 20 } 21 }
标签:nts Fix exec 有一个 另一个 [] max 服务器 传递
原文地址:https://www.cnblogs.com/Mao-admin/p/9989248.html