JAVA并发编程3

说明:先上代码,笔记后续补充。
public class ExecutorTest1 {

//Executor 线程池
//Executor是一个接口 只能执行任务,没有关闭的方法
/**
* ExecutorService是子类(也是个接口) 提供了关闭的方法
* void shutdown();比较柔性的关闭,停止接收新任务,如果还有线程在执行,会等待线程执行结束在关闭
* List<Runnable> shutdownNow(); 强制关闭 返回值就是直接被干掉的线程
* boolean isShutdown(); 判断是否已经关闭,调用了shutdowm就会处于shutdown状态
* boolean isTerminated(); 判断是否终止状态 所有线程执行结束
*
*
* public ThreadPoolExecutor(
* int corePoolSize, 核心线程数
* int maximumPoolSize, 最大线程数
* long keepAliveTime, 线程存活时间
* TimeUnit unit, 时间单位↑
* BlockingQueue<Runnable> workQueue 工作队列
* )
*/

static ExecutorService executor = Executors.newCachedThreadPool();

public static void main(String[] args) throws IOException {
//能容纳100个线程的线程池
// Executor executor = Executors.newFixedThreadPool(100);
//单一线程的线程池,池中只有一个线程,如果备占用则等待,如果这个线程有问题或者挂了,则会出现一个新的异常
// Executor executor = Executors.newSingleThreadExecutor();
//缓冲线程池,池中线程数量不确定,无上限(有风险)
//
// Executors.newScheduledThreadPool()
ServerSocket serverSocket = new ServerSocket(80);
while (!executor.isShutdown()){
Socket socket = serverSocket.accept();
try {
executor.execute(new Runnable() {
@Override
public void run() {
handleRequest(socket);
}
});
} catch (RejectedExecutionException e) {
if (!executor.isShutdown()){
System.out.println("线程池接收任务失败。。。");
throw e;
}

}
}
}
public void stop(){
executor.shutdown();
}

public static void handleRequest(Socket socket) {
System.out.println("访问成功");
}
}

猜你喜欢

转载自www.cnblogs.com/sleepy-goblin/p/8910035.html