Executor与TreadPoolExecutor

1.allowsCoreThreadTimeOut()方法

  没有任务时,将线程池中的线程停掉。并且这个方法是允许线程数低于corePoolSize时,线程也因为空闲而终止。

 1 package Four_allowsCoreThreadTimeOut_demo;
 2 
 3 public class MyRunnable implements Runnable {
 4 
 5     @Override
 6     public void run() {
 7         // TODO Auto-generated method stub
 8 
 9         System.out.println(Thread.currentThread().getName() + " begin " + System.currentTimeMillis());
10 
11         System.out.println(Thread.currentThread().getName() + " end " + System.currentTimeMillis());
12     }
13 
14 }
 1 package Four_allowsCoreThreadTimeOut_demo;
 2 
 3 import java.util.concurrent.SynchronousQueue;
 4 import java.util.concurrent.ThreadPoolExecutor;
 5 import java.util.concurrent.TimeUnit;
 6 
 7 public class Test1 {
 8 
 9     public static void main(String[] args) throws InterruptedException {
10         ThreadPoolExecutor pool = new ThreadPoolExecutor(4, 5, 5, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
11 
12         System.out.println(pool.allowsCoreThreadTimeOut());
13 
14         for (int i = 0; i < 4; i++) {
15             MyRunnable my = new MyRunnable();
16             pool.execute(my);
17         }
18 
19         Thread.sleep(8000);
20 
21         System.out.println(pool.getPoolSize());
22     }
23 
24 }

运行结果:

 1 package Four_allowsCoreThreadTimeOut_demo;
 2 
 3 import java.util.concurrent.SynchronousQueue;
 4 import java.util.concurrent.ThreadPoolExecutor;
 5 import java.util.concurrent.TimeUnit;
 6 
 7 public class Test2 {
 8 
 9     public static void main(String[] args) throws InterruptedException {
10         ThreadPoolExecutor pool = new ThreadPoolExecutor(4, 5, 5, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
11 
12         pool.allowCoreThreadTimeOut(true);
13 
14         System.out.println(pool.allowsCoreThreadTimeOut());
15 
16         for (int i = 0; i < 4; i++) {
17             MyRunnable my = new MyRunnable();
18             pool.execute(my);
19         }
20 
21         Thread.sleep(8000);
22 
23         System.out.println(pool.getPoolSize());
24     }
25 
26 }

运行结果:

 

posted @ 2021-04-01 20:59  L1998  阅读(78)  评论(0)    收藏  举报