I have a question regarding static synchronized methods and class level locking. Can someone please help me in explaining this example:
class Test
{
synchronized static void printTest(int n)
{
for (int i = 1; i <= 10; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception ignored) {}
}
}
}
class MyThread1 extends Thread
{
public void run()
{
Test.printTest(1);
}
}
class MyThread2 extends Thread
{
public void run()
{
Test.printTest(10);
}
}
public class TestSynchronization
{
public static void main(String[] args)
{
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
Question:
When thread t1
is in the middle of loop (inside printTest()
) and I want to make it stop the execution and transfer the control to thread t2
.
Is there any way to do it?
Since we deal with class level lock I believe we cannot use object level wait()
and notify()
methods here which would release the object level lock. But in case of class level lock, how to release it and give the control to some other waiting thread?
How do we notify a second thread which is waiting for a class level lock held by thread 1 in the middle of execution?