线程池介绍

来源:互联网 发布:防范sql注入攻击的方法 编辑:程序博客网 时间:2024/05/29 19:23

线程池主要干什么的呢?

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

线程池的基本思想

线程池的基本思想就是一种对象池的思想,说白了就是开辟一块内存空间,然后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 0