package com.dcrj.thread; |
import java.util.concurrent.*; |
public class ThreadFourDemo { |
public static void main(String[] args) { |
//使用线程池的工厂方法类创建线程池 |
//fixedThreadPool(); |
//scheduledThreadPool(); |
threadExecutorPool(); |
} |
public static void fixedThreadPool() { |
ThreadFour threadFour = new ThreadFour(); |
//手动创建固定线程数的线程池 |
ExecutorService executorService = Executors.newFixedThreadPool( 3 ); |
//submit提交任务并执行,带回返回值的任务 |
//execute执行任务不要返回值 |
//执行的是任务个数 |
for ( int i = 0 ; i < 10 ; i++) { |
executorService.execute(threadFour); |
} |
} |
public static void scheduledThreadPool() { |
ThreadFour threadFour = new ThreadFour(); |
//手动创建固定线程数的线程池 |
ScheduledExecutorService executorService = Executors.newScheduledThreadPool( 5 ); |
//submit提交任务并执行,带回返回值的任务 |
//execute执行任务不要返回值 |
//执行的是任务个数 |
for ( int i = 0 ; i < 7 ; i++) { |
executorService.schedule(threadFour, 2 , TimeUnit.SECONDS); |
} |
executorService.shutdown(); |
} |
/*** |
* 最终线程池的使用 |
* */ |
public static void threadExecutorPool() { |
ThreadFour threadFour = new ThreadFour(); |
ThreadPoolExecutor threadPoolExecutor1 = new ThreadPoolExecutor( 2 , |
5 , |
2 , |
TimeUnit.HOURS, |
new ArrayBlockingQueue<Runnable>( 5 )); |
for ( int i = 0 ; i < 10 ; i++) { |
threadPoolExecutor1.execute(threadFour); |
} |
} |
} |