线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。
public class ThreadPoolTest {
//1、不用线程池
//函数式接口实现,重写run
public static void noPool(){
Runnable target=()->{
for (int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
};
//手动创建两个线程并启动
//传入一个Runnable实例作为target
new Thread(target).start();
new Thread(target).start();
}
//2、使用线程池
public static void usePool(){
//不需要自己创建线程,只需要创建线程池,将target(要执行的任务)提交给线程池,线程池就会分配两个空闲的线程来执行
ExecutorService pool= Executors.newFixedThreadPool(6);
Runnable target=()->{
for (int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
};
//向线程池提交两个线程
pool.submit(target);
pool.submit(target);
//关闭线程池
pool.shutdown();
}
public static void main(String[] args) {
noPool();
usePool();
}
}
Thread-1:0
Thread-1:1
Thread-1:2
Thread-0:0
Thread-1:3
Thread-0:1
Thread-1:4
Thread-0:2
Thread-1:5
Thread-0:3
Thread-1:6
Thread-1:7
Thread-0:4
Thread-0:5
Thread-0:6
Thread-1:8
Thread-0:7
Thread-0:8
Thread-1:9
Thread-0:9
pool-1-thread-2:0
pool-1-thread-1:0
pool-1-thread-2:1
pool-1-thread-1:1
pool-1-thread-2:2
pool-1-thread-1:2
pool-1-thread-2:3
pool-1-thread-1:3
pool-1-thread-2:4
pool-1-thread-1:4
pool-1-thread-2:5
pool-1-thread-1:5
pool-1-thread-2:6
pool-1-thread-1:6
pool-1-thread-2:7
pool-1-thread-1:7
pool-1-thread-2:8
pool-1-thread-1:8
pool-1-thread-2:9
pool-1-thread-1:9