JDK1.5中线程池,定时器知识

时间:2023-03-09 08:00:48
JDK1.5中线程池,定时器知识

package cn.it.pool;

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

public class ThreadPoolTest {

public static void main(String[] args) {
//创建固定大小的线程池
ExecutorService service1=Executors.newFixedThreadPool(3);
//创建缓存线程池
ExecutorService service2=Executors.newCachedThreadPool();
//创建单一线程池,如果此线程死掉会创建另一个线程接替此线程完成任务,从而
//实现线程死掉又重启启动功能
ExecutorService service3=Executors.newSingleThreadExecutor();

//定时器功能
//5秒之后爆炸一次,之后不爆炸
Executors.newScheduledThreadPool(1).schedule(
new Runnable() {
@Override
public void run() {
System.out.println("bombing!!!");
}
}, 
5, 
TimeUnit.SECONDS);
//5秒之后第一次爆炸,之后每隔一秒爆炸一次
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
System.out.println("bombing!!!");
}
}, 
5, 
1,
TimeUnit.SECONDS);
}
}