I have the following sample piece of code,
public class test implements Runnable{
public void run()
{
synchronized(this)
{
for(int i=0;i<10000;i++)
System.out.println(i);
}
}
public static void main(String args[]) throws Exception
{
Thread t=new Thread(new test());
t.start();
//Thread.sleep(100);
t.suspend();
System.out.println("Hi");
}
}
I have the following requirement,When the thread is suspended it must execute all the iterations of the loop without getting suspended. I felt that synchronized is for this purpose but it didnot solve the problem. When i suspend a thread if it is in a synchronized block then it must get suspended only after the block is executed. What java construct can be used for this?
In Java, when a piece of code is in
synchronizedblock, only one thread can execute this block at once. In order to suspend a thread only after it has finished its synchronized block, just synchronized over the same variable:Note that both blocks in
run()andmain()synchronize over the same variable (instance ofTest). Now the code in synchronized block inmain()will be executed only after the work inrun()is done.(Please note however, that there is some race condition here: you cannot guarantee that after
t.start()the code inrun()will actually execute before the next line of code inmain())