I also tried with Exception and did not get any error.
Now for first prog:
<pre>
class Reetrant{
String s=new String();
//String thrdName ;
public void a(){
String thrdName;
thrdName = Thread.currentThread().getName();
//synchronized(thrdName){
System.out.println(thrdName);
synchronized(this){
try{
System.out.println(thrdName + ": B4 sleep()");
Thread.sleep(1000);
//wait(100);
// Thread.yield();
}catch(Exception e){
//1.Doubt
}
b(thrdName);
//b();
System.out.println(thrdName + ": In a");
synchronized(s){
System.out.println(thrdName + ": In syn block");
}
Thread.yield();
}// end synch block
//}
synchronized(this){
try{
System.out.println(thrdName + ": B4 sleep() after first sync and in second sync");
Thread.sleep(1000);
//wait(100);
}catch(Exception e){
//1.Doubt
}
}
System.out.println(thrdName + ": end of a()");
}// end if method a()
public void b(String thrdName){
//public void b(){
System.out.println(thrdName + ": in b WT sync");
//synchronized(thrdName ){
synchronized(s){
System.out.println(thrdName + ": in b");
}
//}
}
} // end of Reetrant
class Synchr1 implements Runnable{
Reetrant r1 = new Reetrant();
public static void main(String args[]){
Synchr1 s1=new Synchr1();
//Synchr1 s2=new Synchr1();
Thread t1=new Thread(s1,"FirstThred");
Thread t2=new Thread(s1,"SecondThread");
//Thread t2=new Thread(s2,"SecondThread");
t1.start();
t2.start();
}
public void run(){
r1.a();
}
}
</pre>
you can remove comments and then put comments on yield() and/or wait() and/or sleep() to see what happens...
Now when you synchronize an object for a block then same object can not run the same block of statement.
sleep() does leave the lock so even a thread is sleeping it does not realease the lock.
but if you try wait(long time) or yield() you can find that other thread starts executing.
condition is that object should be same.
if you have s2 object reference then there will be no problem as there will be two different objects.
for ur second program:
there are three (if u include main thread also then 4)threads are running. one which start in main(), other two are starts by the thread u created. They are created by using
annonymous class.
code is like
<pre>
new Thread() // no name for the class
{ public void run() { // overriding method run() for annonymous class
// some code
}.start() // register with the thread schedular( call the run() )
</pre>
correct me if wrong.
[This message has been edited by ravish kumar (edited October 19, 2001).]