import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Executors 线程池学习
* 线程池的思想还是一种对象池的思想、开辟一块内存空间来管理众多的未死亡的线程,
* 池中的线程调度由线程池来管理。当线程有任务的时候从线程中取出一个进行任务,完成以后归还给对象池,
* 这样可以避免反复的创建线程对象所带来的性能开销,节省资源。
*/
public class Main {
public static void main(String[] args) {
//创建一个可重用固定线程数的线程池
//ExecutorService pools = Executors.newFixedThreadPool(5); //固定大小的任务线程池
//ExecutorService pools = Executors.newSingleThreadExecutor(); //单任务线程池
//ExecutorService pools = Executors.newCachedThreadPool(); //可变尺寸线程池
ScheduledExecutorService pools = Executors.newScheduledThreadPool(2);//延迟连接池
//创建线程
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
// MyThread t4 = new MyThread();
//MyThread t5 = new MyThread();
//将线程放入池中进行执行
pools.execute(t1);
//pools.execute(t2);
//pools.execute(t3);
//pools.execute(t4);
//pools.execute(t5);
//使用延迟执行的方法风格
pools.schedule(t2,1000, TimeUnit.MILLISECONDS);
pools.schedule(t3,10,TimeUnit.MILLISECONDS);
//关闭线程池
pools.shutdown();
}
}
Executors
最新推荐文章于 2025-01-26 10:23:00 发布