Java多线程编程-线程池的使用

创建线程池一般有一下几种方法:

    ThreadPoolExecutor pool=new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());  创建线程池类,自己定义参数

 Executors.newFixedThreadPoo()l创建的线程池corePoolSize和maximumPoolSize值是相等的,它使用的LinkedBlockingQueue;

   Executors.newSingleThreadExecutor()将corePoolSize和maximumPoolSize都设置为1,也使用的LinkedBlockingQueue;
  
  Executors.newCachedThreadPool()将corePoolSize设置为0,将maximumPoolSize设置为Integer.MAX_VALUE,使用的SynchronousQueue,也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程。
 
  实际中,如果Executors提供的三个静态方法能满足要求,就尽量使用它提供的三个方法,因为自己去手动配置ThreadPoolExecutor的参数有点麻烦,要根据实际任务的类型和数量来进行配置。

package demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //创建线程池类,自己定义参数
        //ThreadPoolExecutor pool=new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        //使用静态方法
        ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newFixedThreadPool(5);//corePoolSize和maxiPoolSize都为5
        //ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newCachedThreadPool();
        //ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newSingleThreadExecutor();

        for(int i=0;i<5;i++){
            Thread thread=new Thread(new MyThread("Thread:"+i));
            pool.execute(thread);
        }

    }

}

class MyThread implements Runnable{

    private String  threadName;
    public MyThread(String name) {
        // TODO Auto-generated constructor stub
        threadName=name;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("我是线程:"+threadName);
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值