您的位置:首页 > 产品设计 > UI/UE

ArrayBlockingQueue和ExecutorService的理解与感悟

2015-06-02 10:59 232 查看
package test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test {
public static void main(String[] args) {
//executorServiceTest()
arrayBlockingQueueTest();
}
public static void arrayBlockingQueueTest(){
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5);
ThreadPoolExecutor executor=new ThreadPoolExecutor(3, Runtime.getRuntime().availableProcessors(), 1,
TimeUnit.HOURS, queue,new ThreadPoolExecutor.CallerRunsPolicy());
for(int i=0;i<100;i++){
final int index=i;
System.out.println("task:"+(i+1));
Runnable run=new Runnable() {
@Override
public void run() {
System.out.println("thread start" + index);
try {
Thread.sleep(1000*3);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("thread end "+index);
}
};
executor.execute(run);
}
}
public static void executorServiceTest(){
ExecutorService service = Executors.newFixedThreadPool(2);
for(int i=0;i<100;i++){
final int index=i;
System.out.println("task:"+(i+1));
Runnable run=new Runnable() {
@Override
public void run() {
System.out.println("thread start" + index);
try {
Thread.sleep(1000*3);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("thread end "+index);
}
};
service.execute(run);
}

}
}


调用executorServiceTest方法的运行结果

task:1
task:2
task:3
thread start0
task:4
task:5
thread start1
task:6
task:7
task:8
task:9
task:10
thread end 0
thread start2
thread end 1
thread start3
thread end 2
thread end 3
thread start4
thread start5
thread end 5
thread start6
thread end 4
thread start7
thread end 6
thread end 7
thread start8
thread start9
thread end 8
thread end 9


调用arrayBlockingQueueTest运行结果

task:1
task:2
task:3
thread start0
thread start1
task:4
thread start2
task:5
task:6
task:7
thread start6
thread end 1
thread end 6
thread end 0
thread end 2
thread start5
thread start4
task:8
task:9
thread start3
task:10
thread end 5
thread end 3
thread end 4
thread start9
thread start8
thread start7
thread end 9
thread end 8
thread end 7


从运行的结果看,不难看出用ExecutorService的话是将所有的线程调用起来,放在内存中。

而ArrayBlockingQueue的话是线程有个容量,从运行结果看是4个,这样实现了自动阻塞队列的效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: