1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger;
public class Solution { public static void main(String[] args) { int corePoolSize = 2; int maximumPoolSize = 4; long keepAliveTime = 10L;
ThreadPoolExecutor pool = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new CustomThreadFactory(), new ThreadPoolExecutor.AbortPolicy() );
for (int i = 0; i < 10; i++) { pool.execute(new Task(i)); }
pool.shutdown(); try { if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { pool.shutdownNow(); } } catch (InterruptedException ex) { pool.shutdownNow(); Thread.currentThread().interrupt(); } } }
class CustomThreadFactory implements ThreadFactory { private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix = "pool-";
@Override public Thread newThread(Runnable r) { return new Thread(r, namePrefix + threadNumber.getAndIncrement()); } }
class Task implements Runnable { private final int taskId;
public Task(int taskId) { this.taskId = taskId; }
@Override public void run() { System.out.println(Thread.currentThread().getName() + " is executing task " + taskId); try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
|