public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
//固定线程池的方式ExecutorService threadPool = Executors.newFixedThreadPool(3);
//缓存线程池的方式ExecutorService threadPool = Executors.newCachedThreadPool();
//单个线程池,注意,单个线程池,当它死掉后会自动重启
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i=1;i<=10;i++){
final int task = i;
threadPool.execute(new Runnable(){
@Override
public void run() {
for(int j=1;j<=10;j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task);
}
}
});
}
System.out.println("all of 10 tasks have committed! ");
threadPool.shutdownNow();
// 下面这种方式是用线程池的方式来模拟定时器的效果
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}},
6,
2,
TimeUnit.SECONDS);
}
}
java线程池
最新推荐文章于 2025-06-04 10:45:10 发布