-
ExecutorService
ExecutorService是Java中对线程池定义的一个接口,它java.util.concurrent
包中。Java API对ExecutorService接口的实现有两个(ThreadPoolExecutor和ScheduledThreadPoolExecutor),所以这两个即是Java线程池具体实现类。除此之外,ExecutorService还继承了Executor
接口(注意区分Executor接口和Executors工厂类),这个接口只有一个execute()
方法。下面是继承树。
PS:Executors只是一个工厂类,它所有的方法返回的都是ThreadPoolExecutor
、ScheduledThreadPoolExecutor
这两个类的实例。一共可以创建四种线程池:
首先建立一个线程。
package com.threadpool.thread;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class TestThread implements Runnable{
/**
* 线程私有属性,创建线程时创建
*/
private Integer num = 0;
public TestThread(Integer num) {
this.num = num;
}
@Override
public void run() {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("thread:" + Thread.currentThread().getName() + ",time:" + sdf1.format(new Date()) + ",num:" + num);
try {
//使线程睡眠,模拟线程阻塞情况
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
1. newCachedThreadPool
创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
package com.threadpool.executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.threadpool.thread.TestThread;
public class CachedThreadPoolTest {
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for(int i = 0 ; i < 50 ; i++){
cachedThreadPool.submit(new TestThread((i + 1)));
}
cachedThreadPool.shutdown();
}
}
2. newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
package com.threadpool.executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.threadpool.thread.TestThread;
public class FixedThreadPoolTest {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
for(int i = 0 ; i < 50 ; i++){
fixedThreadPool.submit(new TestThread((i + 1)));
}
fixedThreadPool.shutdown();
}
}
3. newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。
package com.threadpool.executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
//定时
// scheduledThreadPool.schedule(new Runnable() {
// @Override
// public void run() {
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// System.out.println("thread:" + Thread.currentThread().getName() + ",time:" + sdf1.format(new Date()));
// }
// }, 3, TimeUnit.SECONDS);
//循环周期执行
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);
}
}
4. newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
package com.threadpool.executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.threadpool.thread.TestThread;
public class SingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
for(int i = 0 ; i < 50 ; i++){
singleThreadPool.submit(new TestThread((i + 1)));
}
singleThreadPool.shutdown();
}
}
为什么要用线程池:
1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
2.可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。
Java里面线程池的顶级接口是Executor,但是严格意义上讲Executor并不是一个线程池,而只是一个执行线程的工具。真正的线程池接口是ExecutorService。