Menu

#4 thread pool

open
nobody
None
5
2014-08-21
2008-08-13
Anonymous
No

the main code in run method

public synchronized void run() {
while(true) {
if (s == null) {
/* nothing to do */
try {
wait();
} catch (InterruptedException e) {
/* should not happen */
continue;
}
}
try {
handleClient();
} catch (Exception e) {
e.printStackTrace();
}
/* go back in wait queue if there's fewer
* than numHandler connections.
*/
s = null;

/**
* this pool is a reference to the same vector threads
* both pool and threads are vector and both are required
* to be synchronized thats why we have synchronized botth
* thread and pool
*/

Vector pool = mainThreadedServer.threads;

/**
* pool and threads are referencing the same vector instance
*/

synchronized (pool)
{

System.out.println\(" worker"+Thread.currentThread\(\)\);
/\*\*
 \* here pool.size\(\) is actually giving the the size of vector thread
 \* from where we have renoved one thread from 0 position
 \*/

if \(pool.size\(\) >= mainThreadedServer.workers\)
\{

/* too many threads, exit this one wait for one worker thread to be ready in the pool */
return;
}

else
\{
/\*\*
 \* since pool is a reference to the same vector  threads 
 \* the added threads are actually added to the thread pool
 \* means from start end we are removing threads and at the 
 \* last end we are adding threads  
 \*/

pool.addElement(this);

System.out.println(" worker"+Thread.currentThread());

/**
* this is the thread which invoked the run method and this thread is added
* at the last of the vector threads
*/
}
}
}
}

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.