四种Java线程池用法解析

本文为你们分析四种Java线程池用法,供你们参考,具体内容以下java

http://www.jb51.net/article/81843.htm数据库

一、new Thread的弊端缓存

执行一个异步任务你还只是以下new Thread吗?安全

?
1
2
3
4
5
6
7
8
new Thread( new Runnable() {
 
   @Override
   public void run() {
     // TODO Auto-generated method stub
     }
   }
).start();

那你就out太多了,new Thread的弊端以下:服务器

a. 每次new Thread新建对象性能差。
b. 线程缺少统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源致使死机或oom。
c. 缺少更多功能,如定时执行、按期执行、线程中断。并发

相比new Thread,Java提供的四种线程池的好处在于:app

a. 重用存在的线程,减小对象建立、消亡的开销,性能佳。
b. 可有效控制最大并发线程数,提升系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、按期执行、单线程、并发数控制等功能。异步

二、Java 线程池ide

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
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() {
 
@Override
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
ExecutorService fixedThreadPool = Executors.newFixedThreadPool( 3 );
   for ( int i = 0 ; i < 10 ; i++) {
   final int index = i;
 
   fixedThreadPool.execute( new Runnable() {
 
@Override
public void run() {
try {
   System.out.println(index);
   Thread.sleep( 2000 );
} catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   }
}
});
}

由于线程池大小为3,每一个任务输出index后sleep 2秒,因此每两秒打印3个数字。

定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。可参考PreloadDataCache。

(3)newScheduledThreadPool:

建立一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码以下:

?
1
2
3
4
5
6
7
8
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool( 5 );
  scheduledThreadPool.schedule( new Runnable() {
 
@Override
public void run() {
   System.out.println( "delay 3 seconds" );
}
}, 3 , TimeUnit.SECONDS);

表示延迟3秒执行。

按期执行示例代码以下:

?
1
2
3
4
5
6
7
scheduledThreadPool.scheduleAtFixedRate( new Runnable() {
 
@Override
public void run() {
   System.out.println( "delay 1 seconds, and excute every 3 seconds" );
}
}, 1 , 3 , TimeUnit.SECONDS);

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

ScheduledExecutorService比Timer更安全,功能更强大

(4)newSingleThreadExecutor:

建立一个单线程化的线程池,它只会用惟一的工做线程来执行任务,保证全部任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码以下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for ( int i = 0 ; i < 10 ; i++) {
final int index = i;
singleThreadExecutor.execute( new Runnable() {
 
@Override
public void run() {
   try {
     System.out.println(index);
   Thread.sleep( 2000 );
} catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
     }
}
   });
}

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

现行大多数GUI程序都是单线程的。Android中单线程可用于数据库操做,文件操做,应用批量安装,应用批量删除等不适合并发但可能IO阻塞性及影响UI线程响应的操做。

线程池的做用:

线程池做用就是限制系统中执行线程的数量。
根 据系统的环境状况,能够自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了形成系统拥挤效率不高。用线程池控制线程数量,其余线程排 队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务须要运行时,若是线程池 中有等待的工做线程,就能够开始运行了;不然进入等待队列。

为何要用线程池:

1.减小了建立和销毁线程的次数,每一个工做线程均可以被重复利用,可执行多个任务。

2.能够根据系统的承受能力,调整线程池中工做线线程的数目,防止由于消耗过多的内存,而把服务器累趴下(每一个线程须要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。

Java里面线程池的顶级接口是Executor,可是严格意义上讲Executor并非一个线程池,而只是一个执行线程的工具。真正的线程池接口是ExecutorService。

比较重要的几个类:

ExecutorService: 真正的线程池接口。

ScheduledExecutorService: 能和Timer/TimerTask相似,解决那些须要任务重复执行的问题。

ThreadPoolExecutor: ExecutorService的默认实现。

ScheduledThreadPoolExecutor: 继承ThreadPoolExecutor的ScheduledExecutorService接口实现,周期性任务调度的类实现。

要配置一个线程池是比较复杂的,尤为是对于线程池的原理不是很清楚的状况下,颇有可能配置的线程池不是较优的,所以在Executors类里面提供了一些静态工厂,生成一些经常使用的线程池。

1.newSingleThreadExecutor

建立一个单线程的线程池。这个线程池只有一个线程在工做,也就是至关于单线程串行执行全部任务。若是这个惟一的线程由于异常结束,那么会有一个新的线程来替代它。此线程池保证全部任务的执行顺序按照任务的提交顺序执行。

2.newFixedThreadPool

建立固定大小的线程池。每次提交一个任务就建立一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,若是某个线程由于执行异常而结束,那么线程池会补充一个新线程。

3.newCachedThreadPool

建立一个可缓存的线程池。若是线程池的大小超过了处理任务所须要的线程,

那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增长时,此线程池又能够智能的添加新线程来处理任务。此线程池不会对线程池大小作限制,线程池大小彻底依赖于操做系统(或者说JVM)可以建立的最大线程大小。

4.newScheduledThreadPool

建立一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

实例代码

1、固定大小的线程池,newFixedThreadPool:

 

?
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
30
31
32
33
34
35
36
37
package app.executors;
 
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
 
/**
  * Java线程:线程池
  *
  * @author xiho
  */
public class Test {
   public static void main(String[] args) {
     // 建立一个可重用固定线程数的线程池
     ExecutorService pool = Executors.newFixedThreadPool( 2 );
     // 建立线程
     Thread t1 = new MyThread();
     Thread t2 = new MyThread();
     Thread t3 = new MyThread();
     Thread t4 = new MyThread();
     Thread t5 = new MyThread();
     // 将线程放入池中进行执行
     pool.execute(t1);
     pool.execute(t2);
     pool.execute(t3);
     pool.execute(t4);
     pool.execute(t5);
     // 关闭线程池
     pool.shutdown();
   }
}
 
class MyThread extends Thread {
   @Override
   public void run() {
     System.out.println(Thread.currentThread().getName() + "正在执行。。。" );
   }
}

输出结果:

?
1
2
3
4
5
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 3 正在执行。。。
pool- 1 -thread- 4 正在执行。。。
pool- 1 -thread- 2 正在执行。。。
pool- 1 -thread- 5 正在执行。。。

改变ExecutorService pool = Executors.newFixedThreadPool(5)中的参数:ExecutorService pool = Executors.newFixedThreadPool(2),输出结果是:

?
1
2
3
4
5
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 2 正在执行。。。
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 2 正在执行。。。

从以上结果能够看出,newFixedThreadPool的参数指定了能够运行的线程的最大数目,超过这个数目的线程加进去之后,不会运行。其次,加入线程池的线程属于托管状态,线程的运行不受加入顺序的影响。

2、单任务线程池,newSingleThreadExecutor:

仅仅是把上述代码中的ExecutorService pool = Executors.newFixedThreadPool(2)改成ExecutorService pool = Executors.newSingleThreadExecutor();
输出结果:

?
1
2
3
4
5
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 1 正在执行。。。

能够看出,每次调用execute方法,其实最后都是调用了thread-1的run方法。

3、可变尺寸的线程池,newCachedThreadPool:

与上面的相似,只是改动下pool的建立方式:ExecutorService pool = Executors.newCachedThreadPool();

输出结果:

?
1
2
3
4
5
pool- 1 -thread- 1 正在执行。。。
pool- 1 -thread- 2 正在执行。。。
pool- 1 -thread- 4 正在执行。。。
pool- 1 -thread- 3 正在执行。。。
pool- 1 -thread- 5 正在执行。。。

这种方式的特色是:可根据须要建立新线程的线程池,可是在之前构造的线程可用时将重用它们。

4、延迟链接池,newScheduledThreadPool:

 

?
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
30
31
32
33
34
35
public class TestScheduledThreadPoolExecutor {
 
   public static void main(String[] args) {
 
     ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor( 1 );
 
     exec.scheduleAtFixedRate( new Runnable() { //每隔一段时间就触发异常
 
            @Override
 
            publicvoid run() {
 
               //throw new RuntimeException();
 
               System.out.println( "================" );
 
            }
 
          }, 1000 , 5000 , TimeUnit.MILLISECONDS);
 
     exec.scheduleAtFixedRate( new Runnable() { //每隔一段时间打印系统时间,证实二者是互不影响的
 
            @Override
 
            publicvoid run() {
 
               System.out.println(System.nanoTime());
 
            }
 
          }, 1000 , 2000 , TimeUnit.MILLISECONDS);
 
   }
 
}

输出结果:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
================
 
8384644549516
 
8386643829034
 
8388643830710
 
================
 
8390643851383
 
8392643879319
 
8400643939383

以上就是本文的所有内容,但愿对你们的学习有所帮助。

相关文章
相关标签/搜索