Understand the thread pool and implement a thread pool yourself

Source: Internet
Author: User

The thread pool essence is a producer-consumer model that maintains some threads to perform tasks while adding some tasks from the main thread. Now we discard the source of some complex state judgment, write a thread pool.

 Public classPoolt {
It is possible to delete tasks frequently, and the list queue efficiency is highPrivate FinalBlockingqueue<runnable> WorkQueue =NewLinkedblockingqueue<runnable>(); Private FinalHashset<work> workers =NewHashset<work>(); Private Static intnum = 3; PublicPoolt (intnum) { This. num =num; for(inti = 0; i < num; i++) {Work W=NewWork (); W.start (); Workers.add (w); } } Public voidAddwork (Runnable R) {Workqueue.add (R); } Public voidClose ()throwsException { while(!Workqueue.isempty ()) {Thread.Sleep (500); } for(Work work:workers) {//notification is running at the endWork.setdrop (); //the end of the force is still waiting. if(work.getstate () = =Thread.State.WAITING) {work.interrupt (); }} thread.sleep (2000); for(Work work:workers) {System.out.println (Work.getname ()+ "Status:" +work.getstate ()); } } //Internal Thread Encapsulation Private classWorkextendsThread {Runnable R=NULL; //end thread Flag bit Private BooleanHasrunning =true; Public voidSetdrop () { This. hasrunning =false; } Public voidrun () {Try { while(Hasrunning | |!Workqueue.isempty ()) { //Blocking Thread ExecutionR =Workqueue.take (); if(r! =NULL) {r.run (); } } } Catch(Exception e) {e.printstacktrace (); } } } Public Static voidMain (string[] args)throwsException {Poolt P=NewPoolt (4); for(inti = 0; I < 2; i++) {Runnable Newrun=NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000); System.out.println (Thread.CurrentThread (). GetName ()+ "Run task;"); } Catch(interruptedexception e) {e.printstacktrace (); } } }; P.addwork (Newrun); } p.close (); System.out.println ("Main program Complete"); }}

I used a blocking queue, and when the task was added, it was randomly picked up by the queue for processing by a free thread, and blocked when there was no task.

Of course, you can not block the queue, but you need to synchronize

 Public classMythreadpool {List<Runnable> taskList =NewLinkedlist<runnable>(); PrivateList<mythread> threadlist =NewLinkedlist<mythread>(); Private StaticMythreadpool ThreadPool;  PublicMythreadpool (intnum) {         for(inti = 0; i < num; i++) {Threadlist.add (NewMyThread ()); }         for(MyThread thread:threadlist) {Thread.Start (); }    }       Public voiddestroy () { while(!tasklist.isempty ()) {//If there's still a job to do, just go to sleep.                Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); }              }              //worker thread stops working and is set to null             for(MyThread thread:threadlist) {Thread.setdistroy (); }        }             Public voidExecute (Runnable run) {synchronized(taskList) {tasklist.add (run);        Tasklist.notify (); }    }    Private classMyThreadextendsThread { Public BooleanHasrun =true; Private voidSetdistroy () { This. Hasrun =false; } @Override Public voidrun () { while(hasrun) {Runnable R=NULL; System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); synchronized(taskList) {if(Tasklist.isempty () &&Hasrun) {                        Try{tasklist.wait (20); } Catch(interruptedexception e) {e.printstacktrace (); }                    } Else{R= Tasklist.remove (0); }                }                if(r! =NULL) {r.run (); }            }        }    }     Public Static voidMain (string[] args)throwsException {//Executorservice Excutor=executors.newfixedthreadpool (3);Mythreadpool pool =NewMythreadpool (4); Pool.execute (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (500); System.out.println ("Task One"); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        }); Pool.execute (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (500); System.out.println ("Task Ii."); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        }); System.out.println ("End");    Pool.destroy (); }}

Reference: http://blog.csdn.net/hsuxu/article/details/8985931

Understand the thread pool and implement a thread pool yourself

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.