In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "the specific usage of ThreadPoolExecutor thread pool". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
ThreadPoolExecutor
ThreadPoolExecutor thread pool, java provides a development framework to manage thread creation, destruction, optimization, monitoring, and so on.
There are four different task queues:
1.ArrayBlockingQueue: a task queue based on an array structure. This queue sorts tasks on a first-in-first-out basis.
2.LinkedBlockingQueue: task queue based on linked list structure. This queue also sorts tasks on a first-in-first-out basis. But the performance is higher than that of ArrayBlockingQueue.
3.synchronousQueue: a task queue that does not store elements. Each insert operation must wait until another thread invokes the remove operation, otherwise the insert operation remains blocked.
4.PriorityBlockingQueue: a task queue with priority. Elements in this queue must be comparable.
Reject Policy:
RejectedExecutionHandler (saturation strategy): when the number of threads in the thread pool is greater than maximumPoolSize, the thread pool can no longer handle any tasks, and the thread pool throws an exception. The reason is that this policy defaults to AbortPolicy: it means that an exception is thrown when a new task cannot be processed.
1.AbortPolicy: throw an exception directly.
2.CallerRunsPolicy: only use the caller's thread to run the task.
3.DiscardOldestPolicy: discards the most recent task in the queue and executes the current task
4.DiscardPolicy: don't deal with it, discard it. Custom: ThreadPoolExecutor.AbortPolicy () / throw java.util.concurrent.RejectedExecutionException exception ThreadPoolExecutor.CallerRunsPolicy () / retry to add the current task, he will automatically repeatedly call the execute () method ThreadPoolExecutor.DiscardOldestPolicy () / / discard the old task ThreadPoolExecutor.DiscardPolicy () / / discard the current task
Private static class RecjectThreadHandler implements RejectedExecutionHandler {@ Override public void rejectedExecution (Runnable r, ThreadPoolExecutor executor) {} / / exception logging private void doLog (Runnable r, ThreadPoolExecutor executor) {System.out.println (r.toString () + "excutor failed." + executor.getCompletedTaskCount ());}}
Create a thread factory:
Used to create threads.
Public class CheckThreadFactory implements ThreadFactory {private String threadGroupName; private AtomicInteger count = new AtomicInteger (0); public CheckThreadFactory (String threadGroupName) {this.threadGroupName = threadGroupName;} @ Override public Thread newThread (Runnable r) {Thread thread = newThread (r); thread.setName (threadGroupName+ "- -" + count.addAndGet (1)); thread.setPriority (5); thread.setDaemon (true);. / / set to daemon thread, default to main thread return thread;}}
Threading tool class:
/ * @ author Donald * @ create 2019-09-21 21:40 * / public class CheckExcetPool {/ / number of core threads in the thread pool private static int corePoolSize = Runtime.getRuntime (). AvailableProcessors () * 5; / / maximum number of threads private static int maximumPoolSize = corePoolSize > 255? 255: corePoolSize * 2; / / maximum survival time for threads other than core threads in the thread pool private static int keepAliveTime = 60; / / time unit private static TimeUnit timeUnit = TimeUnit.SECONDS / / Thread waiting queue private static BlockingQueue queue = new LinkedBlockingQueue (); / / private static BlockingQueue queue = new ArrayBlockingQueue (30); / / the factory where the thread was created private static CheckThreadFactory checkThreadFactory = new CheckThreadFactory ("checkGroup") / / reject strategy when the number of tasks submitted exceeds the sum of the maxmumPoolSize+workQueue, / / * that is, when the 41st task is submitted (none of the previous threads have finished execution, sleep is used in this test method), / / * the task will be handed over to RejectedExecutionHandler to handle / * handler rejection strategy: there are four kinds of AbortPolicy: first, do not execute a new task, but directly throw an exception to indicate that the thread pool is full. Second DisCardPolicy: do not execute a new task. Third DisCardOldSetPolicy: replace the first task in the message queue with the current new task to execute the fourth CallerRunsPolicy: directly call execute to execute the current task * / private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor (corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, queue, checkThreadFactory) Public static void submit (Runnable runnable) {System.out.println (corePoolSize+ "::" + queue.size ()); threadPoolExecutor.submit (runnable);} public static Future submit (Callable callable) {return threadPoolExecutor.submit (callable);} public static void excutor (Runnable run, T result) {threadPoolExecutor.submit (run,result);} public static void excutor (Runnable run) {threadPoolExecutor.execute (run) } private static class RecjectThreadHandler implements RejectedExecutionHandler {@ Override public void rejectedExecution (Runnable r, ThreadPoolExecutor executor) {} / / exception logging private void doLog (Runnable r, ThreadPoolExecutor executor) {System.out.println (r.toString () + "excutor failed." + executor.getCompletedTaskCount ());}
Thread service class, which implements the runnable interface:
/ * @ author Donald * @ create 2019-09-21 23:00 * / public class ThreadService implements Runnable {private CountDownLatch countDownLatch; private UserInterface userInterface; public ThreadService (CountDownLatch countDownLatch, UserInterface userInterface) {this.countDownLatch = countDownLatch; this.userInterface = userInterface;} @ Override public void run () {try {long start = System.currentTimeMillis (); userInterface.doSomething (); System.err.println ("user time:% s", System.currentTimeMillis ()-start); Thread.sleep (1000) } catch (Exception e) {e.printStackTrace ();} finally {countDownLatch.countDown ();}
Specific business logic:
/ * author Donald * @ create 2019-09-21 22:51 * / public interface UserInterface {void doSomething ();}
Business category:
/ * @ author Donald * @ create 2019-09-21 22:51 * / public class UserService implements UserInterface {private int number; public UserService (int number) {this.number = number;} @ Override public void doSomething () {System.out.println (Thread.currentThread (). GetName () + "
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.