`
qinxike
  • 浏览: 23216 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
ExecutorService executorservice Executor--JCIP C06读书笔记
class LifecycleWebServer { 
    private final ExecutorService exec = ...; 
 
    public void start() throws IOException { 
        ServerSocket socket = new ServerSocket(80); 
        while (!exec.isShutdown()) { 
            try { 
                final Socket conn = socket.accept(); 
                exec.execute(new Runnable() { 
                    public void run() { handleRequest(conn); } 
                }); 
            } catch (RejectedExecutionException e) { 
		// 线程池关闭后提交任务将抛出RejectedExecutionException异常
                if (!exec.isShutdown()) 
                    log("task submission rejected", e); 
            } 
        } 
    } 
 
    public void stop() { exec.shutdown(); } 
 
    void handleRequest(Socket connection) { 
        Request req = readRequest(connection); 
	// 如果是关闭请求, 就关闭线程池, 否则分发该请求
        if (isShutdownRequest(req)) 
            stop(); 
        else 
            dispatchRequest(req); 
    } 
} 
Executor executor Executor--JCIP C06读书笔记
class TaskExecutionWebServer { 
    private static final int NTHREADS = 100; 
    // 创建线程池
    private static final Executor exec 
        = Executors.newFixedThreadPool(NTHREADS); 
 
    public static void main(String[] args) throws IOException { 
        ServerSocket socket = new ServerSocket(80); 
        while (true) { 
            final Socket connection = socket.accept(); 
            Runnable task = new Runnable() { 
                public void run() { 
                    handleRequest(connection); 
                } 
            }; 
	    // 将任务提交给线程池执行
            exec.execute(task); 
        } 
    } 
}
Global site tag (gtag.js) - Google Analytics