package JavaThread;
import java.util.Date;
import java.util.Random;
/**
* 这是一个简单的Runnable类,需要大约5秒钟来执行其任务。
*
*/
public class MyRunnable implements Runnable {
private String command;
public MyRunnable(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Time = " + new Date());
processCommand();
System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());
}
private void processCommand() {
Random random = new Random();
try {
Thread.sleep(random.nextInt(10) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.command;
}
}
package JavaThread;
import java.util.concurrent.*;
public class ThreadPoolExecutorDemo {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
public static void main(String[] args) throws InterruptedException {
//使用阿里巴巴推荐的创建线程池的方式
//通过ThreadPoolExecutor构造函数自定义参数创建
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 10; i++) {
//创建WorkerThread对象(WorkerThread类实现了Runnable 接口)
Runnable worker = new MyRunnable("" + i);
//执行Runnable
executor.execute(worker);
}
printThreadPoolStatus(executor);
//终止线程池
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
public static void printThreadPoolStatus(ThreadPoolExecutor threadPool) {
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
scheduledExecutorService.scheduleAtFixedRate(() -> {
System.out.println("=========================");
System.out.println(String.format("ThreadPool Size: [%s]", threadPool.getPoolSize()));
System.out.println(String.format("Active Threads: %s", threadPool.getActiveCount()));
System.out.println(String.format("Number of CompletedTasks : %s", threadPool.getCompletedTaskCount()));
System.out.println(String.format("Number of Tasks in Queue: %s", threadPool.getQueue().size()));
System.out.println(String.format("Number of CorePoolSize: %s", threadPool.getCorePoolSize()));
System.out.println(String.format("Number of LargestPoolSize: %s", threadPool.getLargestPoolSize()));
System.out.println(String.format("Number of MaximumPoolSize: %s", threadPool.getMaximumPoolSize()));
System.out.println(String.format("========================="));
}, 0, 1, TimeUnit.SECONDS);
}
}