线程池的作用:
限制系统中执行线程的数量,减少内存的消耗,减轻服务器负荷。
newFixedThreadPool
ExecutorService pool=Executors.newFixedThreadPool(2);
Thread t1=new Thread(new ThreadDemo1("线程A"));
Thread t2=new Thread(new ThreadDemo1("线程B"));
Thread t3=new Thread(new ThreadDemo1("线程C"));
Thread t4=new Thread(new ThreadDemo1("线程D"));
//放入线程池
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
//关闭线程池
pool.shutdown();
newCachedThreadPool
ExecutorService pool=Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
final int index=i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.execute(new Runnable(){
@Override
public void run() {
System.out.println(index);
}});
}
![](https://i-blog.csdnimg.cn/blog_migrate/4f591e1e66cfe9d1f530157073efad08.png)
newScheduledThreadPool
ScheduledExecutorService pool=Executors.newScheduledThreadPool(5);
pool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("延迟3秒");
}
}, 3, TimeUnit.SECONDS);
pool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("延迟1秒,每个执行3秒");
}
}, 1, 3, TimeUnit.SECONDS);
![](https://i-blog.csdnimg.cn/blog_migrate/b5c795dc5b78fdcce6512e5d9b8c7b87.png)
newSingleThreadExecutor
ExecutorService singleThreadExecutor=Executors.newSingleThreadExecutor();
for(int i=0;i<5;i++){
final int index=i;
singleThreadExecutor.execute(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+" : "+index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}});
}
![](https://i-blog.csdnimg.cn/blog_migrate/bb9260e4d4b5ae9fcd4ea1b17a4d425d.png)