线程池介绍

线程池主要干什么的呢?

线程池主要为了节省系统的资源的,为什么这么说呢,因为当有线程任务的时候,就从线程池中拿一个,用完了在放回去,这样就避免了重复创建线程从而带来系统性能的开销。

线程池的基本思想

线程池的基本思想就是一种对象池的思想,说白了就是开辟一块内存空间,然后new适当的线程对象,然后将对象放在池子里面,用的时候从池子里面拿,用完了在还回去。

如何创建一个线程池?

线程池分两种:一种是固定尺寸的线程池,一种是可变尺寸的线程池。

固定尺寸的线程池:

package com.lilei;

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

public class TestExcutor {
    public static void main(String[] args) {
        //创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
        ExecutorService pool = Executors.newFixedThreadPool(2);
        MyThread1 th1 = new MyThread1();
        MyThread1 th2 = new MyThread1();
        MyThread1 th3 = new MyThread1();
        MyThread1 th4 = new MyThread1();
        MyThread1 th5 = new MyThread1();
        //将线程放入到线程池中执行
        pool.execute(th1);
        pool.execute(th2);
        pool.execute(th3);
        pool.execute(th4);
        pool.execute(th5);
    }
}
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"正在执行......");
    }
}

固定尺寸的线程池还有一种单任务线程池,只要改动上面一个小小的地方,就是 将ExecutorService pool = Executors.newFixedThreadPool(2); 改成`ExecutorService pool = Executors.newSingleThreadExecutor();

可变尺寸的线程池,其实也只是改一行代码就行了,和单任务线程池一样改成ExecutorService pool = Executors.newCachedThreadPool(); 这个样子就ok了,是不是很简单。

延迟连接池,也是改动上面那个例子的代码,例子如下:

package com.lilei;

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

public class TestExcutor {
    public static void main(String[] args) {
        //创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
        //ExecutorService pool = Executors.newFixedThreadPool(2);
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        MyThread1 th1 = new MyThread1();
        MyThread1 th2 = new MyThread1();
        MyThread1 th3 = new MyThread1();
        MyThread1 th4 = new MyThread1();
        MyThread1 th5 = new MyThread1();
        //将线程放入到线程池中执行
        pool.execute(th1);
        pool.execute(th2);
        pool.execute(th3);
//      pool.execute(th4);
//      pool.execute(th5);
        pool.schedule(th4, 10, TimeUnit.SECONDS);// thread time seconds
        pool.schedule(th5, 10, TimeUnit.SECONDS);
    }
}
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"正在执行......");
    }
}

并没有重新写一个例子,而是在固定线程池的例子上改的,仅仅需要改动其中几行代码。其实固定尺寸和可变尺寸的线程就只有new出来的线程池对象不同,其他的好像没什么区别。
还有一个单任务延迟线程池和自定义线程池其实一样的,也差不多,有兴趣的可以看看jdk文档。上面有很详细的介绍。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值