持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情
使用newCachedThreadPool(ThreadFactory)定制线程工厂
无界线程池中的Thread类可以定制,方法newCachedThreadPool(ThreadFactory)是指定对应线程工厂。
线程工厂类实现代码如下:
public class TheThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("定制线程工厂中的线程对象的名称:"+Math.random());
return thread;
}
}
运行类代码如下:
public class ThreadFactoryRun {
public static void main(String[] args) {
TheThreadFactory theThreadFactory = new TheThreadFactory();
ExecutorService executorService = Executors.newCachedThreadPool(theThreadFactory);
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 在运行时间: "+System.currentTimeMillis());
}
});
}
}
运行结果如下:
定制线程工厂中的线程对象的名称:0.17919848640354485 在运行时间: 1653879919262
从运行结果看出通过自定义的ThreadFactory接口实现类,实现了线程对象的定制。
使用newFixedThreadPool(int)方法创建有界线程池
方法newFixedThreadPool(int)创建的是有界线程池,池中的线程个数可指定最大数量。
实现代码如下:
public class TheRunnable implements Runnable {
private String username;
public TheRunnable(String username){
super();
this.username=username;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() +" username= "+username+" 开始时间:"+System.currentTimeMillis());
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() +" username= "+username+" 结束时间:"+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:
pool-1-thread-1 username= 1 开始时间:1653882113691
pool-1-thread-2 username= 2 开始时间:1653882113691
pool-1-thread-1 username= 1 结束时间:1653882115698
pool-1-thread-1 username= 3 开始时间:1653882115699
pool-1-thread-2 username= 2 结束时间:1653882115699
pool-1-thread-2 username= 4 开始时间:1653882115700
pool-1-thread-1 username= 3 结束时间:1653882117715
pool-1-thread-2 username= 4 结束时间:1653882117715
从运行结果看出最多只有2个线程在运行。使用有界线程池后线程池中的最多线程个数是可控制的。
使用newFixedThreadPool(int,ThreadFactory)定制线程工厂
有界线程池中的Thread类可以定制,方法newFixedThreadPool(int nThreads,ThreadFactory threadFactory)可以执行对应的线程工厂。