The code for writing a thread connection pool in java is as follows:
- Thread Pool:
- Import java. util. Collections list;
- Public abstract class Manager {
- Private String mThreadPoolName = null;
- Private int mThreadPoolMaxSize = 1;
- Private worker list workers = new worker list ();
- Public Manager (){
- }
- Public Manager (String name, int poolMaxSize ){
- MThreadPoolName = name;
- CreateWorker (name, poolMaxSize );
- MThreadPoolMaxSize = poolMaxSize;
- }
- Private void createWorker (int poolMaxSize ){
- For (int I = 0; I <poolMaxSize; I ){
- Worker worker = new... Worker (this );
- Workers. addLast (worker );
- }
- }
- Public synchronized Worker getIdleWorker (){
- Return (Worker) workers. removeFirst ();
- }
- Public synchronized void policyfree (Worker worker ){
- If (workers. size () <mThreadPoolMaxSize ){
- Workers. addLast (worker );
- } Else {
- Worker = null;
- }
- }
- Public int getThreadPoolMaxSize (){
- Return mThreadPoolMaxSize;
- }
- Public void setThreadPoolMaxSize (int threadPoolMaxSize ){
- This. mThreadPoolMaxSize = threadPoolMaxSize;
- }
- }
- Thread abstract class
- Public abstract class Worker implements Runnable {
- Private Manager mManager = null;
- Private Thread mThread = null;
- Public Worker (){
- }
- Public Worker (String threadName, Manager manager ){
- MManager = manager;
- MThread = new Thread (this, threadName );
- Init ();
- & Nb