Posted By:
Carsten_Reckord
Posted On:
Thursday, March 21, 2002 08:07 AM
Hi, I'd like to know if the Thread.start() method does acquire any locks during its execution. My problem is that sometimes my multi-threading application freezes because a call to Thread.start() does not return. The parts of the code that are involved are similar to the code below(considering synchronization and thread execution) import java.util.*; public class Test { public static ThreadContainer threadContainer = new ThreadContainer(); public static boolean stop = false; private static class ThreadA extends Thread { public void run () { for (int i = 0; i < 35; i++) {
More>>
Hi,
I'd like to know if the
Thread.start()
method does acquire any locks during its execution.
My problem is that sometimes my multi-threading application freezes because a call to
Thread.start()
does not return.
The parts of the code that are involved are similar to the code below(considering synchronization and thread execution)
import java.util.*;
public class Test
{
public static ThreadContainer threadContainer = new ThreadContainer();
public static boolean stop = false;
private static class ThreadA extends Thread
{
public void run ()
{
for (int i = 0; i
< 35; i++)
{
ThreadC threadC=threadContainer.createThread();
} // for
threadContainer.startThreads();
stop = true;
}
}
private static class ThreadB extends Thread
{
public void run ()
{
Random random = new Random();
while ( !stop )
{
try
{
// wait a bit so threadA already has the lock
Thread.sleep(random.nextInt(300)+150);
} // try
catch (InterruptedException e )
{
} // try-catch
threadContainer.createThread();
} // while
}
}
private static class ThreadC extends Thread
{
public void run ()
{
while ( !stop )
{
//do something
} // while
}
}
private static class ThreadContainer
{
private transient final Object threadListLock = new Object ();
private LinkedList threadList = new LinkedList();
public ThreadC createThread ()
{
synchronized(threadListLock)
{
ThreadC threadC=new ThreadC();
threadList.add(threadC);
return threadC;
}
}
public void startThreads()
{
synchronized (threadListLock)
{
Iterator iter=threadList.iterator();
while ( iter.hasNext() )
{
ThreadC threadC=(ThreadC)iter.next();
threadC.start();
} // while
}
}
}
public static void main (String[] args)
{
ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
b.start();
a.start();
Thread.yield();
} // main ()
}
The problem is that while ThreadA is in the start-loop in method
startThreads
ThreadB tries to enter method
createThread
and in that situation it sometimes happens that the
Thread.start()
method does not return...
Regards,
Carsten
PS: Note however that this problem does not occur (for some reason I don't understand) in the code above which is much simpler than my original code...
<<Less