Executor | 最基本的线程池接口。 |
---|---|
ExecutorService | 线程接口的扩展 |
Executors | 创建各种需要类型的线程池 |
ThreadPoolExecutor | 继承AbstractExecutorService 实现ExecutorService 方法 |
具体如下图
使用线程池好处:
1、在高并发的时候,降低峰值,避免阻塞,影响性能,最大案例就是京东某年 某次活动的时候,服务器直接罢工。增加服务器和延迟峰值,延迟某些操作即能延迟的 就延迟操作,这两个方面可以缓解高并发问题。
2、统一化管理的优点他都有,就是减少资源的创建 销毁时间,资源的复用
一、Executor
基本的接口类,可以执行runable的实现类。把线程加入队列的过程。
public interface Executor {
void execute(Runnable command);
}
案例:
public class TaskExecutionWebServer {
//设置线程数量的界限
private static final int MTHREDS = 100;
//创建一个固定长度的线程池。每次提交一个就创建一个,直至最大线程数量。
private static final Executor exec = Executors.newFixedThreadPool(MTHREDS);
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(8080);
while (true) {
final Socket connection = socket.accept();
Runnable taskRunnable = new Runnable() {
@Override
public void run() {
// handleRequest(connection);
}
};
//添加到线程池,线程队列,等待执行。
exec.execute(taskRunnable);
}
}
}
二、ExecutorService
继承Executor 接口,扩展了Future等,方法。可以是线程单向运行即创建->调用->运行->结束。使用状态不可逆行。 可以添加callable线程方法。
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
.....
}
三 Executors
工具类:,对线程池的实现辅助。提供线程池的创建。
public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newSingleThreadExecutor()
public static ExecutorService newCachedThreadPool()
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
四、ThreadPoolExecutor
线程池类,对线程池的流程的关键类,继承AbstractExecutorService 类。
public abstract class AbstractExecutorService implements ExecutorService {
}
public class ThreadPoolExecutor extends AbstractExecutorService {
}
五、CallBack
/*
java.util.concurrent.Callable<Object>
A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
The Callable interface is similar to java.lang.Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
The Executors class contains utility methods to convert from other common forms to Callable classes.
See Also:
Executor
*/
/**
给的解释就是相对于runnable + 返回
即获取线程执行的过程。
*/
class CallBackDemo{
private static final int MTHREDS = 100;
private static final ExecutorService exec = Executors.newFixedThreadPool(MTHREDS);
final ArrayList<Object> infoList=new ArrayList<Object>();
public void test(){
Callable<Object> tasks=new Callable<Object>() {
@Override
public Object call() throws Exception {
return null;
}
};
Future<Object> future= exec.submit(tasks);
}
}