线程池的用法

为什么用线程池呢?
这个问题很容易理解。池者,容器也。线程池把设置到池中的线程管理起来。提高了系统的稳定性和线程的可控性。下面是本人写的一个线程小例子,通过Timer来反应线程池的机制。
package phl;

import java.io.Serializable;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* phl 2010-4-24
* 这段程序演示了线程池 和定时线程的作用关系
* 本例中,线程池只允许一个线程执行,其他线程将加到队列中等待执行.
*
*/
public class Timer_ThreadPoolExecutor {

/**
ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)

corePoolSize: 线程池维护线程的最少数量
maximumPoolSize:线程池维护线程的最大数量
keepAliveTime:线程池维护线程所允许的空闲时间
unit: 线程池维护线程所允许的空闲时间的单位
workQueue:线程池所使用的缓冲队列
handler: 线程池对拒绝任务的处理策略
*/
//方法一:不推荐
private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
1,
1,
3,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(3),
new ThreadPoolExecutor.DiscardOldestPolicy());
//方法二:推荐使用这种方法
private ExecutorService threadPool2 = Executors.newFixedThreadPool(5);

public static void main(String[] args) throws Exception {

Timer timer1 = new Timer();
TimerTask task1 = new TimerTask() {
public void run() {
threadPool.execute(new ThreadTask("11111 timer1"));
}
};
timer1.schedule(task1, 0, 1000 * 5);


Timer timer2 = new Timer();
TimerTask task2 = new TimerTask() {
public void run() {
threadPool.execute(new ThreadTask("22222 timer2"));
}
};
timer2.schedule(task2, 0, 1000 * 5);
}
}

class ThreadTask implements Runnable, Serializable {
private String name = "";

public ThreadTask(String name) {
this.name = name;
}

public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " is running!");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值