package com.example.demo.thread; import org.junit.jupiter.api.Test; import java.util.Date; import java.util.concurrent.*; public class ThreadFactoryTest { /** * 記錄線程執行的時間 */ static class MyLogThread extends Thread { private Date createTime; private Date startTime; private Date endTime; public MyLogThread(Runnable runnable, String s) { super(runnable, s); this.createTime = new Date(); } @Override public void run() { this.startTime = new Date(); super.run(); this.endTime = new Date(); } } /** * 自定義線程工廠 */ static class MyThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable runnable) { return new MyLogThread(runnable, "MyLogThread"); } } @Test public void Test1() { ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); executor.setThreadFactory(new MyThreadFactory()); } //--------------------------------------------- //爲Fork/Join框架生成定製線程 static class MyWorkerThread extends ForkJoinWorkerThread { private static ThreadLocal<Integer> taskCounter = new ThreadLocal<>(); protected MyWorkerThread(ForkJoinPool forkJoinPool) { super(forkJoinPool); } /** * */ @Override protected void onStart() { super.onStart(); System.out.printf("MyWorkerThread %d:Initializing task counter.\n", getId()); taskCounter.set(0); } /** * @param throwable */ @Override protected void onTermination(Throwable throwable) { System.out.printf("MyWorkerThread %d:%d\n", getId(), taskCounter.get()); super.onTermination(throwable); } public void addTask() { int counter = taskCounter.get().intValue(); counter++; taskCounter.set(counter); } } static class MyWorkThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory { @Override public ForkJoinWorkerThread newThread(ForkJoinPool forkJoinPool) { return null; } } static class MyTask extends RecursiveTask<String> { @Override protected String compute() { MyWorkerThread workerThread = (MyWorkerThread) Thread.currentThread(); workerThread.addTask(); //something to do return null; } } @Test public void test2() { MyWorkThreadFactory factory = new MyWorkThreadFactory(); ForkJoinPool pool = new ForkJoinPool(4, factory, null, false); pool.execute(new MyTask()); pool.shutdown(); pool.awaitQuiescence(1, TimeUnit.HOURS); } }