利用Executors创建所需要的缓存类型
package cn.zto.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//线程池
public class TestThreadPool {
public static void main(String[] args) {
//创建有3个线程的线程池
//ExecutorService service = Executors.newFixedThreadPool(3);
//创建一个线程缓存池 根据需要的线程数 而 创建线程
ExecutorService service = Executors.newCachedThreadPool();
//创建一个只有一个线程的线程池,如果线程死亡 则会重新搞个线程
//ExecutorService service = Executors.newSingleThreadExecutor();
for (int i = 1; i <= 10; i++) {
final int count = i;
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 5; i++) {
System.out.println("第"+i+"次循环,在"+count+"任务中");
}
}
});
}
service.shutdown();
}
}
利用Executors创建所需要的缓存类型
package cn.zto.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//线程池
public class TestThreadPool {
public static void main(String[] args) {
//创建有3个线程的线程池
//ExecutorService service = Executors.newFixedThreadPool(3);
//创建一个线程缓存池 根据需要的线程数 而 创建线程
ExecutorService service = Executors.newCachedThreadPool();
//创建一个只有一个线程的线程池,如果线程死亡 则会重新搞个线程
//ExecutorService service = Executors.newSingleThreadExecutor();
for (int i = 1; i <= 10; i++) {
final int count = i;
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 5; i++) {
System.out.println("第"+i+"次循环,在"+count+"任务中");
}
}
});
}
service.shutdown();
}
}