连接池定义
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 }