多线程之线程池newFixedThreadPool

创建固定大小的线程池的时候使用ThreadFactory

public static ExecutorService newFixedThreadPool( int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }


ThreadFactory的作用:构造一个新 Thread。实现也可能初始化属性、名称、守护程序状态、ThreadGroup 等等。

在写demo的时候,我认为最麻烦的就是,设置循环中创建的线程的join方法。 在没有使用线程池的时候,在循环中调用这个方法都麻烦,要么抛出异常,要么就只有再循环一次来单独设置。 就这个场景而言,使用ThreadFactory来就很简单了。 ——————– 好把,我以为在工厂中,自己调用join方法能行。但是测试过了。视乎没有效果。 那就只能看下用法。场景用途我暂时也不知道了

示例如下:

/**
 * Created by zhuqiang on 2015/8/25 0025.
 */
public class Client {
    public static void main(String[] args) {
//        ThreadPoolExecutor es = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);  //1 该注释代码。和下面为使用工厂的对比。
        ThreadPoolExecutor es = (ThreadPoolExecutor) Executors.newFixedThreadPool(3, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("xxxx" + thread.getId());  //对新创建的线程做一些操作
                return thread;
            }
        });
        for (int i = 0; i < 10 ; i++) {
            es.execute(new Task(es,"task-"+i));
        }
        es.shutdown();
    }
}
class Task implements  Runnable{
    private  ThreadPoolExecutor es;
    private  String name;

    public Task(ThreadPoolExecutor es, String name) {
        this.es = es;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            long timeout = (long) (Math.random() * 10);
            TimeUnit.SECONDS.sleep(timeout);
            System.out.println(Thread.currentThread().getName() + "...执行完成..task=" + name +"    耗时:" + timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值