java中创建线程池有哪几种方式呢?
下文笔者讲述使用java代码创建线程池的方法分享,如下所示
使用 Executors 工具类创建线程池
Executors提供了一系列工厂方法用于创先线程池
返回的线程池都实现了ExecutorService接口
主要有newSingleThreadExecutor,newFixedThreadPool,newCachedThreadPool,newScheduledThreadPool
实现思路:
方式1:使用Executors工具类创建线程池
方式2:使用ThreadPoolExecutor构造函数创建线程池
例:使用 Executors 工具类创建线程池
Executors提供了一系列工厂方法用于创先线程池
返回的线程池都实现了ExecutorService接口
主要有newSingleThreadExecutor,newFixedThreadPool,newCachedThreadPool,newScheduledThreadPool
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " run()方法执行中...");
}
}
public class SingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
MyRunnable runnableTest = new MyRunnable();
for (int i = 0; i < 5; i++) {
executorService.execute(runnableTest);
}
System.out.println("线程任务开始执行");
executorService.shutdown();
}
}
运行以上代码,将输出以下信息
线程任务开始执行 pool-1-thread-1 is running... pool-1-thread-1 is running... pool-1-thread-1 is running... pool-1-thread-1 is running... pool-1-thread-1 is running...
使用ThreadPoolExecutor构造函数创建线程池
public class Task implements Runnable {
private int taskNum;
public Task(int taskNum) {
this.taskNum = taskNum;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 正在执行task " + taskNum);
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " task " + taskNum + "执行完毕");
}
}
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(5));
for (int i = 0; i < 5; i++) {
Task task = new Task(i);
threadPoolExecutor.execute(task);
System.out.println(Thread.currentThread().getName() + " 线程池中线程数目:" + threadPoolExecutor.getPoolSize() + ",队列中等待执行的任务数目:" +
threadPoolExecutor.getQueue().size() + ",已执行完的任务数目:" + threadPoolExecutor.getCompletedTaskCount());
}
threadPoolExecutor.shutdown();
}
}
运行以上代码,将输出以下信息----
pool-1-thread-1 正在执行task 0 main 线程池中线程数目:1,队列中等待执行的任务数目:0,已执行完的任务数目:0 main 线程池中线程数目:2,队列中等待执行的任务数目:0,已执行完的任务数目:0 main 线程池中线程数目:2,队列中等待执行的任务数目:1,已执行完的任务数目:0 main 线程池中线程数目:2,队列中等待执行的任务数目:2,已执行完的任务数目:0 pool-1-thread-2 正在执行task 1 main 线程池中线程数目:2,队列中等待执行的任务数目:3,已执行完的任务数目:0 pool-1-thread-1 task 0执行完毕 pool-1-thread-2 task 1执行完毕 pool-1-thread-1 正在执行task 2 pool-1-thread-2 正在执行task 3 pool-1-thread-2 task 3执行完毕 pool-1-thread-2 正在执行task 4 pool-1-thread-1 task 2执行完毕 pool-1-thread-2 task 4执行完毕
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


