码迷,mamicode.com
首页 > 编程语言 > 详细

线程池的创建

时间:2017-03-23 23:57:44      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:pre   stack   rate   run   tor   ted   current   style   override   

package com.newer.cn;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {

    public static void main(String[] args) {
        // 创建线程池的方式
        
        // 创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程,在需要时使用提供的 ThreadFactory 创建新线程。
        ExecutorService pool = Executors.newFixedThreadPool(5);
        
        // 创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。
        ExecutorService pool1 = Executors.newSingleThreadExecutor();
        
        // 创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。
        ExecutorService pool2 = Executors.newCachedThreadPool();
        
        //创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。
        ExecutorService pool3 = Executors.newScheduledThreadPool(3);

    }

}

举个例子

package com.newer.cn;

public class Demo implements Runnable {

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println("执行当前线程的是:"+name);
        for(int i = 1;i <= 10;i++){
            System.out.println(name+":"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("执行任务完毕");

    }

}
package com.newer.cn;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
         ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 
         for(int i = 1;i <= 5;i++){
             Demo demo = new Demo();
             cachedThreadPool.execute(demo);
         }
        

    }

}

 

线程池的创建

标签:pre   stack   rate   run   tor   ted   current   style   override   

原文地址:http://www.cnblogs.com/lujing-newer/p/6607828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!