1 PackageCom.lovo.threadpool;2 3 Public classThreadofpoolextendsthread{4 PrivateRunnable task =NULL;5 PrivateThreadPool ThreadPool;6 Private BooleanStop =false;//Thread State7 PublicThreadofpool () {8 }9 PublicThreadofpool (ThreadPool ThreadPool) {Ten This. ThreadPool =ThreadPool; One } A /** - * Assign a thread to a specified task - * @paramTask the */ - Public synchronized voidsettask (Runnable Task) { - This. Task =task; - notify (); + } - /** + * Thread Execution A */ at Private synchronized voidExecuteTask () { - while(!stop) { - while(!stop && Task = =NULL) { - Try { - wait (); -}Catch(interruptedexception e) { inStop =true; - } to } + if(Task! =NULL) { - Task.run (); theTask =NULL; *Threadpool.free ( This); $ }Panax Notoginseng } - } the @Override + Public voidrun () { A ExecuteTask (); the } + PublicRunnable Gettask () { - returntask; $ } $ Public voidSetstop (Booleanstop) { - This. Stop =stop; - } the -}
1 PackageCom.lovo.threadpool;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 6 Public classThreadPool {7 PrivateList<thread> freethreads =NewArraylist<thread> ();//idle Thread (available)8 PrivateList<thread> usingthreads =NewArraylist<thread> ();//threads being used (not available)9 Private intPool_size = 5;Ten PublicThreadPool () { One This(pool_size); A } - PublicThreadPool (intnum) { -Pool_size =num; the for(inti = 0; i < pool_size; i++) { -Threadofpool Tempthread =NewThreadofpool ( This); - Tempthread.start (); - Freethreads.add (tempthread); + } - } + /** A * Assigning a thread at * @paramT - */ - Public synchronized voidExecute (Runnable t) { - while(Freethreads.isempty ()) { - //System.out.println ("thread pool busy, please wait!") "); - Try { in wait (); -}Catch(interruptedexception e) { to e.printstacktrace (); + } - } theThreadofpool tempthread= (Threadofpool) Freethreads.remove (Freethreads.size ()-1); * Usingthreads.add (tempthread); $ Tempthread.settask (t);Panax Notoginseng } - /** the * After the allocated thread is exhausted, the recycling process + * @paramThreadofpool A */ the Public synchronized voidFree (Threadofpool threadofpool) { + Usingthreads.remove (threadofpool); - Freethreads.add (threadofpool); $ notify (); $ } - /** - * Close thread pool the */ - Public voidClose () {Wuyi while(Freethreads.size () <pool_size) {} the for(Thread thread:freethreads) { - Thread.Interrupt (); Wu } - } About}
Learning multithreading for the first time--writing a thread pool yourself