hi! When we call the yield() method in a synchronized method, then does it releases the lock?? Try the program given below. In this program as the yield() method is called at //1, the second
thread gets a chance(not always, try to run it 3-4 times, the output would be different) to run and enters in the run() method. In this way the synchronized feature of run() method losts its effect. Can u explain something here?
ashok.
__________
class TestThread extends Thread {
public synchronized void run() {
System.out.println("entered in run");
System.out.println(getPriority());
yield(); //1
System.out.println("end of run");
}
public static void main(
String args[]) {
Thread t = new TestThread();
t.start();
t = new TestThread();
t.start();
}
}
__________
One more thing, i forgot that if we use the class lock in synchronization then calling yield() in the synchronized block doesn't give up the lock, as follows
Even on executing several times, the output shows that lock is not given up, but should we take it as a certain behaviour?)
__________
class fort extends Thread {
public void run() {
synchronized(fort.class) {
System.out.println("entered in run");
yield(); //1
System.out.println("end of run");
}
}
public static void main(String args[]) {
new fort().start();
new fort().start();
}
}