线程池:就是把多个线程放在一起执行一个任务;
创建一个线程池:
代码
package testDemo;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个线程池
ExecutorService exService = Executors.newCachedThreadPool();
for(int x = 0; x < 10; x++) {
int index = x;
exService.submit(() -> {
System.out.println(Thread.currentThread().getName()+ "、x = " + index);
});
}
exService.shutdown();//关闭线程池
}
}
创建单个线程的线程池:newSingleThreadExecutor()
package testDemo;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//创建一个线程池
ExecutorService exService = Executors.newSingleThreadExecutor();
for(int x = 0; x < 10; x++) {
//Thread.sleep(200);
int index = x;
exService.submit(() -> {
System.out.println(Thread.currentThread().getName()+ "、x = " + index);
});
}
exService.shutdown();
}
}
创建固定大小的线程池:newFixedThreadExecutor();
package testDemo;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//创建一个线程池
ExecutorService exService = Executors.newFixedThreadPool(3);
for(int x = 0; x < 10; x++) {
//Thread.sleep(200);
int index = x;
exService.submit(() -> {
System.out.println(Thread.currentThread().getName()+ "、x = " + index);
});
}
exService.shutdown();
}
}
创建定时调度池:
package testDemo;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//创建一个具备有三个大小的定时调度线程池
ScheduledExecutorService exService = Executors.newScheduledThreadPool(1);
for(int x = 0; x < 10; x++) {
//Thread.sleep(200);
int index = x;
exService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+ "、= " + index);
}
},3, 2, TimeUnit.SECONDS);//使用的是一个秒的单位,每三秒执行一次
}
}
}