纸上谈兵之一 线程池的创建

首先来看下线程池的接口

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}
Executor是基于生产者-消费者模式,提交任务的操作相当于生成者,执行任务的相当于消费者。

我以书中的例子来说明线程池的创建

public class TaskExecutionWebServer {
	  private static final int NTHREADS = 10;
	  private static final Executor exec = Executors.newFixedThreadPool(NTHREADS);
	/** 
	 * @Title: main 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param args    设定文件 
	 * @return void    返回类型 
	 * @throws 
	 * @author 闭门车  
	 */
	    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);
	        }
	    }
	    private static void handleRequest(Socket connection) {
	        // request-handling logic here
	    }
}
Executor exec = Executors.newFixedThreadPool(NTHREADS); 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值