--Executors 线程池的顶级接口,实际完成线程池的接口是:ExecutorService;
--为什么使用线程池?
|-使用线程池的目的是为了解决每次创建和销毁线程带来的资源和时间的浪费,与其如此,不如事先先创建好一些线程,放在池子里,以后需要的时候,从池里拿来一个Thread,来处理业务;方便...
--如何使用?
|-Executors提供了几个静态工场,用来创建固定形式的线程池供我们使用;
|-1 Executors.newSingleThreadExecutor() 创建 单线程 线程池;-->相当于 单线程 了
|-2 Executors.newFixedThreadPool(5) 创建 固定个数的 线程池;-->每次执行一个job,调用一个Thread,有固定线程数限制;
|-3 Executors.newCachedThreadPool() 创建 可重用 固定个数 线程池;-->自动的根据需求来合理创建和销毁线程;
上述3中类型线程池的Demo:
package com.bdc;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
public class ThreadPool {
@Test
public void test1(){
/**
* 创建 单线程 线程池
*/
ExecutorService pool = Executors.newSingleThreadExecutor();
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
Thread t6 = new MyThread();
Thread t7 = new MyThread();
Thread t8 = new MyThread();
Thread t9 = new MyThread();
Thread t10 = new MyThread();
Thread t11 = new MyThread();
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.execute(t7);
pool.execute(t8);
pool.execute(t9);
pool.execute(t10);
pool.execute(t11);
//关闭 线程池
pool.shutdown();
}
@Test
public void test2(){
/**
* 创建 固定个数的 线程池
*/
ExecutorService pool = Executors.newFixedThreadPool(5);
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
Thread t6 = new MyThread();
Thread t7 = new MyThread();
Thread t8 = new MyThread();
Thread t9 = new MyThread();
Thread t10 = new MyThread();
Thread t11 = new MyThread();
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.execute(t7);
pool.execute(t8);
pool.execute(t9);
pool.execute(t10);
pool.execute(t11);
//关闭 线程池
pool.shutdown();
}
@Test
public void test3(){
/**
* 创建 可重用 固定个数 线程池
*/
ExecutorService pool = Executors.newCachedThreadPool();
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
Thread t6 = new MyThread();
Thread t7 = new MyThread();
Thread t8 = new MyThread();
Thread t9 = new MyThread();
Thread t10 = new MyThread();
Thread t11 = new MyThread();
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.execute(t7);
pool.execute(t8);
pool.execute(t9);
pool.execute(t10);
pool.execute(t11);
//关闭 线程池
pool.shutdown();
}
}
class MyThread extends Thread{
@Override
public void run(){
System.out.println(Thread.currentThread().getId()+" "+Thread.currentThread().getName()+"正在执行...");
}
}