1、创建无限大小的线程池,newCachedThreadPool()
public class TestDemo {
public static void main(String[] args) throws InterruptedException {
//创建一个线程池模型,但现在里面没有线程
//newCachedThreadPool()创建无限大小的线程池
ExecutorService executorService=Executors.newCachedThreadPool();
for(int x=0;x<10;x++){
Thread.sleep(100);
int index=x;
// executorService.submit(new Runnable(){
//
// @Override
// public void run() {
//
// System.out.println(Thread.currentThread().getName()+",x="+index);
//
// }
// });
//Lambda表达式
executorService.submit(() ->{
System.out.println(Thread.currentThread().getName()+",x="+index);
});//执行线程一个操作
}
executorService.shutdown();
}
}
2、创建单线程池,newSingleThreadExecutor()
public class TestSingle {
public static void main(String[] args) throws InterruptedException {
//newSingleThreadExecutor();创建单线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int x = 0; x < 10; x++) {
//Thread.sleep(100);
int index = x;
// Lambda表达式
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + ",x=" + index);
});// 执行线程一个操作
}
executorService.shutdown();
}
}
3、创建固定大小的线程池,newFixedThreadPool(3);
public class TestDemo3 {
public static void main(String[] args) {
//newFixedThreadPool(3);创建固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int x = 0; x < 10; x++) {
int index = x;
// Lambda表达式
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + ",x=" + index);
});// 执行线程一个操作
}
executorService.shutdown();
}
}
4、创建定时调度线程池,ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
public class TestDemo4 {
public static void main(String[] args) throws InterruptedException {
//创建一个具备三个大小的定时调度线程池
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
for (int x = 0; x < 3; x++) {
int index = x;
//Thread.sleep(100);
executorService.scheduleAtFixedRate(new Runnable() {
//Lambda表达式
// () ->System.out.println
// (Thread.currentThread().getName() + ",x=" + index)
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ",x=" + index);
}
}, 3, 2, TimeUnit.SECONDS);
//TimeUnit.SECONDS使用的是一个秒的单位,表示3秒后开始执行,而后每两秒执行一次
}
}
}