//线程池
public static void main(String[] args) {
//ExecutorService service = Executors.newFixedThreadPool(3);
//在线程池中创建一个线程,这个线程死了,会马上创建一个新的线程
//ExecutorService service = Executors.newSingleThreadExecutor();
ExecutorService service = Executors.newCachedThreadPool();
for (int i = 1; i <= 10; i++) {
final int task = i;
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 1; j <= 10; j++) {
System.out.println("线程" + Thread.currentThread().getName() + "正在执行第" + task
+ "个任务中的第" + j + "次循环");
}
}
});
}
System.out.println("10个任务全部提交完毕");
//任务都完成时,才关闭线程池中的所有线程
service.shutdown();
}
//执行定时任务的线程池
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
service.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行10秒的定时任务");
}
}, 10, 1, TimeUnit.SECONDS);
service.schedule(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行5秒的定时任务");
}
}, 5, TimeUnit.SECONDS);
}