您的位置:首页 > 其它

线程池的使用

2014-05-10 23:28 316 查看
一、使用Executors来创建简单线程池

1、ExecutorService pools = Executors.newCachedThreadPool();

2、ExecutorService pools = Executors.newSingleThreadExecutor();

3、ExecutorService pools = Executors.newFixedThreadPool(3);

每种的不同点看JDK的API

二、使用Executors来创建Scheduled线程池

1、ScheduledExecutorService pools  = Executors.newSingleThreadScheduledExecutor();

2、ScheduledExecutorService pools  = Executors.newScheduledThreadPool(3);

其它创建查看API

三、Demo

package com.yezi.learn.exectors;

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

/**
* Created by yezi on 2014/5/10.
*/
public class ThreadPools {

public static void main(String []args){
//testPools();
//testScheduledPools();
testSingleScheduled();
}

public static void testSingleScheduled(){
ScheduledExecutorService pools = Executors.newSingleThreadScheduledExecutor();
pools.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("bombing");
}
},10,2,TimeUnit.SECONDS); //10秒后执行线程,每隔2秒执行一次
}

public static void testScheduledPools(){
ScheduledExecutorService pools = Executors.newScheduledThreadPool(3); //创建容量为3的线程池
for(int i=0;i<10;i++){
final int task = i;
pools.schedule(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 3; j++) {
try {
Thread.sleep(20);
System.out.println(Thread.currentThread().getName() + "====" + task + "====" + j);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, 2,TimeUnit.SECONDS); //2秒后开始执行线程
}
}

public static void testPools(){
//ExecutorService pools = Executors.newFixedThreadPool(3);
ExecutorService pools = Executors.newSingleThreadExecutor();
//ExecutorService pools = Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
final int task = i;
pools.execute(new Runnable() {
@Override
public void run() {
for(int j=0;j<3;j++){
try {
Thread.sleep(20);
System.out.println(Thread.currentThread().getName()+"===="+task+"===="+j);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
pools.shutdown();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: