第一种:NewCachedThreadPool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewCachedThreadPool {
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
final int index = i;
cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
System.out.println(Thread.currentThread().getName());
}
});
}
}
}
第二种:NewFixedThreadPool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewFixedThreadPool {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 1000; i++) {
final int index = i;
System.out.println(i);
fixedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
}
}
第三种:NewScheduledThreadPool
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class NewScheduledThreadPool {
//表示延迟1秒执行
/*public static void main(String[] args) {
//括号后面的参数是线程的核心数量
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);
for (int i = 0; i < 100; i++) {
scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("delay 1 seconds");
System.out.println(Thread.currentThread().getName());
}
}, 1, TimeUnit.SECONDS);
}
}*/
//表示延迟1秒后每3秒执行一次
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
System.out.println(Thread.currentThread().getName());
}
}, 1, 1, TimeUnit.SECONDS);
}
}
第四种:NewSingleThreadExecutor
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewSingleThreadExecutor {
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
public void run() {
System.out.println(index);
System.out.println(Thread.currentThread().getName());
}
});
}
}
}