您的位置:首页 > 编程语言 > Java开发

9.Java5线程并发库的应用

2015-07-10 12:07 316 查看
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* java5线程并发库的应用
* 线程池工具类 Executors
*
* @author LiTaiQing
*
*/
public class ThreadPoolTest {

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 = 0; j < 10; j++) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
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.shutdown();
//不管所有任务是否都已结束,直接关闭线程池
//threadPool.shutdownNow();
//计时器
//        Executors.newScheduledThreadPool(3).schedule(new Runnable(){
//            @Override
//            public void run() {
//                System.out.println("bombing!");
//            }
//        },
//        6, //时间
//        TimeUnit.SECONDS);//单位

/**
* 固定频率
* 实现6秒以后炸,以后每2秒后爆炸一次
*/
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}
},
6, //时间
2, //时间间隔
TimeUnit.SECONDS);//单位
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: