ExecutorService steps for building multithreading: \
1. Defining thread classes | class Handler implements Runnable{ } |
---|---|
2. Establish an ExecutorService thread pool | ExecutorService executorService = Executors.newCachedThreadPool(); Or int cpuNums = Runtime.getruntime ().availableprocessors (); / / get the current number of CPU system ExecutorService ExecutorService = Executors. NewFixedThreadPool (cpuNums * POOL_SIZE); // The size of the thread pool is usually flexible, depending on system resources |
3. Invoke the thread pool operation | Executorservice.execute (new Handler(socket)); executorService.execute(new Handler(socket)); Executorservice.execute (createTask(I)); // Class Handler implements Runnable{or executorService.execute(createTask(I)); // Private static Runnable createTask(final int taskID)} execute(Runnable object) Such as queue, priority, IDLE timeout, active activation, etc.) |
Several different ExecutorService thread pool objects
1.newCachedThreadPool() | – Reuse a cache pool to check whether there are any previously created threads in the pool. If not, create a new thread and add it to the pool – caching pools are usually used for short duration asynchronous tasks and are not used much in connection-oriented Daemons. – Reuse specifies the reuse thread. The default timeout is 60 seconds. If the IDLE duration exceeds this threshold, the thread instance is terminated and removed from the pool. Note that a thread placed into a CachedThreadPool does not have to worry about terminating; if it is inactive beyond TIMEOUT, it will be terminated automatically. |
---|---|
2. newFixedThreadPool | -newFixedThreadPool is a cacheThreadPool reuse reuse, but a new thread cannot be created at any time. A fixed number of active threads can be created at any point in time, so new threads can only be created in another queue. Until one of the threads in the current thread terminates and is removed from the pool – unlike cacheThreadPool, FixedThreadPool has no IDLE mechanism (it probably does, but it’s certainly very long, depending on upper layer TCP or UDP IDLE mechanisms and so on). A FixedThreadPool is used to call the same underlying pool as a fixed pool, but with different parameters: Fixed The number of threads in the cache pool is fixed and the value is 0 seconds IDLE (none IDLE) The number of threads in the cache pool is 0 to integer. MAX_VALUE(obviously not considering the host resource capacity), and the value is 60 seconds IDLE |
3.ScheduledThreadPool | – Scheduled thread pool – Threads in this pool can be executed by schedule delay, or periodically |
4.SingleThreadExecutor | – A singleton thread can have only one thread in any time pool – Uses the same underlying pool as the cache pool and fixed pool, but the number of threads is 1-1,0 seconds IDLE |
Each of the above thread pools uses Executor’s default thread factory to create threads, or you can define your own thread factory. Here is the default thread factory code:
static class DefaultThreadFactory implements ThreadFactory { static final AtomicInteger poolNumber = new AtomicInteger(1); final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix; DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s ! = null)? s.getThreadGroup() :Thread.currentThread().getThreadGroup(); namePrefix = “pool-” + poolNumber.getAndIncrement() + “-thread-“; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r,namePrefix + threadNumber.getAndIncrement(),0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() ! = Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; }} |
---|
You can also define your own ThreadFactory and add it to the parameters used to create the pool
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { |
---|
Execute () adds Runnable instances to a pool and does some pool size calculations and priority handling. Execute () The execute() method is defined in the Executor interface. There are several implementation classes that define different execute() methods. For example, the ThreadPoolExecutor class (cache,fiexed,single) uses the following execute method:
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); if (poolSize >= corePoolSize || ! addIfUnderCorePoolSize(command)) { if (runState == RUNNING && workQueue.offer(command)) { if (runState ! = RUNNING || poolSize == 0) ensureQueuedTaskHandled(command); } else if (! addIfUnderMaximumPoolSize(command)) reject(command); // is shutdown or saturated } } |
---|