Java 四种线程池

一、线程池简介:

多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。

假设一个服务器完成一项任务所需时间为:T1 创建线程时间,T2 在线程中执行任务的时间,T3 销毁线程时间。

如果:T1 + T3 远大于 T2,则可以采用线程池,以提高服务器性能。

一个线程池包括以下四个基本组成部分:

1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;

2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;

3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;

4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。

线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。

线程池不仅调整T1,T3产生的时间段,而且它还显著减少了创建线程的数目,看一个例子:

假设一个服务器一天要处理50000个请求,并且每个请求需要一个单独的线程完成。在线程池中,线程数一般是固定的,所以产生线程总数不会超过线程池中线程的数目,而如果服务器不利用线程池来处理这些请求则线程总数为50000。一般线程池大小是远小于50000。所以利用线程池的服务器程序不会为了创建50000而在处理请求时浪费时间,从而提高效率。

代码实现中并没有实现任务接口,而是把Runnable对象加入到线程池管理器(ThreadPool),然后剩下的事情就由线程池管理器(ThreadPool)来完成了

二、java类库中提供的线程池简介:

java提供的线程池更加强大,相信理解线程池的工作原理,看类库中的线程池就不会感到陌生了。

\

\

三、Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

 

(1) newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
packagetest;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoolExecutorTest{publicstaticvoidmain(String[]args){ExecutorServicecachedThreadPool=Executors.newCachedThreadPool(); for (inti= 0 ;i< 10 ;i++){finalintindex=i; try {Thread.sleep(index* 1000 );} catch (InterruptedExceptione){e.printStackTrace();}cachedThreadPool.execute(newRunnable(){publicvoidrun(){System.out.println(index);}});}}}
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
   for ( int i = 0 ; i < 10 ; i++) {
    final int index = i;
    try {
     Thread.sleep(index * 1000 );
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    cachedThreadPool.execute( new Runnable() {
     public void run() {
      System.out.println(index);
     }
    });
   }
  }
}

 

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

(2) newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
packagetest;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoolExecutorTest{publicstaticvoidmain(String[]args){ExecutorServicefixedThreadPool=Executors.newFixedThreadPool( 3 ); for (inti= 0 ;i< 10 ;i++){finalintindex=i;fixedThreadPool.execute(newRunnable(){publicvoidrun(){ try {System.out.println(index);Thread.sleep( 2000 );} catch (InterruptedExceptione){e.printStackTrace();}}});}}}
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   ExecutorService fixedThreadPool = Executors.newFixedThreadPool( 3 );
   for ( int i = 0 ; i < 10 ; i++) {
    final int index = i;
    fixedThreadPool.execute( new Runnable() {
     public void run() {
      try {
       System.out.println(index);
       Thread.sleep( 2000 );
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    });
   }
  }
}


因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

 

(3) newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
packagetest;importjava.util.concurrent.Executors;importjava.util.concurrent.ScheduledExecutorService;importjava.util.concurrent.TimeUnit;publicclassThreadPoolExecutorTest{publicstaticvoidmain(String[]args){ScheduledExecutorServicescheduledThreadPool=Executors.newScheduledThreadPool( 5 );scheduledThreadPool.schedule(newRunnable(){publicvoidrun(){System.out.println( "delay3seconds" );}}, 3 ,TimeUnit.SECONDS);}}
package test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool( 5 );
   scheduledThreadPool.schedule( new Runnable() {
    public void run() {
     System.out.println( "delay 3 seconds" );
    }
   }, 3 , TimeUnit.SECONDS);
  }
}


表示延迟3秒执行。

定期执行示例代码如下:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
packagetest;importjava.util.concurrent.Executors;importjava.util.concurrent.ScheduledExecutorService;importjava.util.concurrent.TimeUnit;publicclassThreadPoolExecutorTest{publicstaticvoidmain(String[]args){ScheduledExecutorServicescheduledThreadPool=Executors.newScheduledThreadPool( 5 );scheduledThreadPool.scheduleAtFixedRate(newRunnable(){publicvoidrun(){System.out.println( "delay1seconds,andexcuteevery3seconds" );}}, 1 , 3 ,TimeUnit.SECONDS);}}
package test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool( 5 );
   scheduledThreadPool.scheduleAtFixedRate( new Runnable() {
    public void run() {
     System.out.println( "delay 1 seconds, and excute every 3 seconds" );
    }
   }, 1 , 3 , TimeUnit.SECONDS);
  }
}


表示延迟1秒后每3秒执行一次。

 

(4) newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
packagetest;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoolExecutorTest{publicstaticvoidmain(String[]args){ExecutorServicesingleThreadExecutor=Executors.newSingleThreadExecutor(); for (inti= 0 ;i< 10 ;i++){finalintindex=i;singleThreadExecutor.execute(newRunnable(){publicvoidrun(){ try {System.out.println(index);Thread.sleep( 2000 );} catch (InterruptedExceptione){e.printStackTrace();}}});}}}
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
   for ( int i = 0 ; i < 10 ; i++) {
    final int index = i;
    singleThreadExecutor.execute( new Runnable() {
     public void run() {
      try {
       System.out.println(index);
       Thread.sleep( 2000 );
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    });
   }
  }
}


结果依次输出,相当于顺序执行各个任务。

你可以使用JDK自带的监控工具来监控我们创建的线程数量,运行一个不终止的线程,创建指定量的线程,来观察:
工具目录:C:\Program Files\Java\jdk1.6.0_06\bin\jconsole.exe
运行程序做稍微修改:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
packagetest;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoolExecutorTest{publicstaticvoidmain(String[]args){ExecutorServicesingleThreadExecutor=Executors.newCachedThreadPool(); for (inti= 0 ;i< 100 ;i++){finalintindex=i;singleThreadExecutor.execute(newRunnable(){publicvoidrun(){ try { while ( true ){System.out.println(index);Thread.sleep( 10 * 1000 );}} catch (InterruptedExceptione){e.printStackTrace();}}}); try {Thread.sleep( 500 );} catch (InterruptedExceptione){e.printStackTrace();}}}}
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();
   for ( int i = 0 ; i < 100 ; i++) {
    final int index = i;
    singleThreadExecutor.execute( new Runnable() {
     public void run() {
      try {
       while ( true ) {
        System.out.println(index);
        Thread.sleep( 10 * 1000 );
       }
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    });
    try {
     Thread.sleep( 500 );
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
}


效果如下:

\

选择我们运行的程序:

\

监控运行状态


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值