Simple implementation of the Java thread pool

Source: Internet
Author: User

The use of multithreading and the meaning of the thread pool is needless to say, in order to master the thread pool, the best way is to manually implement it.

First, the realization of ideas

(Cyber Theft map)

In general, all tasks are waiting in the blockingqueue, and the worker is the actual worker.

Second, the Code

1. Thread Pool class

Package Com.ty.thread;
Import
Java.util.HashSet;ImportJava.util.Set;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.LinkedBlockingQueue;/** * @authorTaoyong * @date May 17, 2018 * No hard-hitting code! */ Public classThreadpoolexecutor {//maintain a list of threads PrivateSet<thread> threadlist =NewHashset<thread>(); /** Blocking queues are thread-safe, primarily used in production/consumer scenarios*/ PrivateBlockingqueue<task>Blockingqueue; //number of worker threads in the thread pool Private intPoolsize = 0; //core capacity of the thread pool Private intCoresize = 0; Private BooleanShutDown =false; PublicThreadpoolexecutor (intsize) { This. poolsize =size; Blockingqueue=NewLinkedblockingqueue<>(poolsize); } Public voidExecute (Task Task)throwsinterruptedexception {if(ShutDown = =true) { return; } if(Coresize <poolsize) {Blockingqueue.offer (Task); Produceworker (Task); }Else{blockingqueue.put (Task); } } Private voidProduceworker (Task Task)throwsinterruptedexception {if(Task = =NULL) { Throw NewNullPointerException ("Illegal parameter: The incoming task object is empty!") "); } if(ShutDown = =true) { return; } Thread Thread=NewThread (NewWorker ()); Threadlist.add (thread); Coresize++; Thread.Start (); }
Public voidShutDown () {if(Threadlist = =NULL|| Threadlist.size () = = 0) { return; } ShutDown=true; for(Thread thread:threadlist) {System.out.println (Thread.getname ()+ "Interrupt"); Thread.Interrupt (); } } /** This inner class is actually a work line worker is the actual worker thread that implements the Runnable interface, and takes the task execution from the Blockingqueue through a while (true) loop. * */ classWorkerImplementsRunnable {@Override Public voidrun () { while(true&& ShutDown = =false) { Try{blockingqueue.take (). Dojob (); } Catch(interruptedexception e) {e.printstacktrace (); } } } }}

2. Task class (tasks that need to be thread-processed)

 PackageCom.ty.thread;/** * @authorTaoyong * @date May 17, 2018 * No hard-hitting code! */ Public classTask {//identify tasks with TaskID    Private inttaskId;  PublicTask (inttaskId) {         This. TaskId =taskId; }     Public voidDojob () {System.out.println ("Thread" + thread.currentthread (). GetName () + "Processing Task!" "); }     Public intgetId () {returntaskId; }}

3. Test class

 PackageCom.ty.thread;/** * @authorTaoyong * @date May 17, 2018 * No hard-hitting code! */ Public classThreadpoolexecutortest { Public Static voidMain (string[] args)throwsinterruptedexception {threadpoolexecutor threadpoolexecutor=NewThreadpoolexecutor (3);  for(inti = 0; I < 10; i++) {Task Task=NewTask (i);                        Threadpoolexecutor.execute (Task);    } threadpoolexecutor.shutdown (); }}

4. Operation result

Thread thread-0 is processing the task! Threads Thread2 is working on thetask! Threads Thread0 is working on thetask! Threads Thread1 is working on thetask! Threads Thread2 is working on thetask! Threads Thread2 is working on thetask! Threads Thread1 is working on thetask! Threads Thread2 is working on thetask! Threads Thread0 is working on thetask! Thread-1 interruptthread-0 interruptthread-2 interrupt

When the tenth task is to be processed, the entire thread pool has been shutdown and the entire process is finished.

Simple implementation of the Java thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.