併發編程——java併發包之線程池

鏈接池定義

  java中爲了提升併發度,能夠使用多線程共同執行。可是若是有大量線程短期以內被建立和銷燬,會佔用大量的系統時間,影響系統效率。java

  爲了解決上面的問題,java中引入了線程池,能夠使建立好的線程在指定的時間內由系通通一管理,而不是在執行時建立,執行後就銷燬,從而避免了頻繁建立、銷燬線程帶來的系統開銷。多線程

經常使用的線程池

  • newCachedThreadPool(線程池中線程數量不作限制,能夠動態擴展,能夠指定或不指定線程池中線程多少,每個線程默認失效時間爲60s,即線程空閒後60s會被回收
  • newFixedThreadPool(固定線程數量的線程池,若是超過此數量則阻塞在內部隊列中
  • newSingleThreadExecutor(上例的特例只有1個線程
  • newScheduleThreadPool(建立一個定長的線程池,並且支持定時的以及週期性的任務執行,支持定時及週期性任務執行)併發

應用舉例

 1 package threadPool;
 2 
 3 public class ThreadSample extends Thread {
 4     private String param;
 5     
 6     public ThreadSample(String param) {
 7         this.param = param;
 8     }
 9 
10     @Override
11     public void run() {
12         System.out.println(param);
13     }
14 }
線程類
 1 package threadPool;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.ScheduledExecutorService;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 import org.junit.Test;
 9 
10 public class ThreadPool {
11     
12     @Test
13     public void testCacheThreadPool() throws InterruptedException {
14         ExecutorService service = Executors.newCachedThreadPool();
15         for (int i = 0; i < 10; i++) {
16             Thread sample = new ThreadSample("Thread-" + i);
17             service.execute(sample);
18             sample.join();
19         }
20     }
21     
22     @Test
23     public void testFixThreadPool() throws InterruptedException {
24         ExecutorService service = Executors.newFixedThreadPool(10);
25         for (int i = 0; i < 10; i++) {
26             Thread sample = new ThreadSample("Thread-" + i);
27             service.execute(sample);
28             sample.join();
29         }
30     }
31     
32     @Test
33     public void testSingleThreadPool() throws InterruptedException {
34         ExecutorService service = Executors.newSingleThreadExecutor();
35         for (int i = 0; i < 10; i++) {
36             Thread sample = new ThreadSample("Thread-" + i);
37             service.execute(sample);
38             sample.join();
39         }
40     }
41     
42     @Test
43     public void testScheduleThreadPool() throws InterruptedException {
44         ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
45         Thread sample = new ThreadSample("Thread");
46         service.scheduleWithFixedDelay(sample, 5, 3, TimeUnit.SECONDS);
47         
48         Thread.sleep(20*1000);
49     }
50 }
線程池使用舉例
相關文章
相關標籤/搜索