Reputation: 49
I was testing the concept of multi threading using these three classes.
This class consists of methods executed by threads.
class MainClass {
static MainClass mainClass;
String name = "Sibendu";
MainClass()
{
mainClass = this;
}
public static void main(String args[])
{
new MainClass();
ThreadImpl thread = new ThreadImpl(mainClass);
ThreadImpl2 thread2 = new ThreadImpl2(mainClass);
thread.start();
thread2.start();
}
public void printMyName() throws InterruptedException {
String name = "Sibendu";
synchronized (name) {
System.out.println("Inside printMyName()");
Thread.sleep(4000);
System.out.println(name);
}
}
public void printMyName2() throws InterruptedException {
synchronized (name) {
System.out.println("Inside printMyName2()");
Thread.sleep(4000);
System.out.println(name);
}
}
}
The two threads:
class ThreadImpl extends Thread {
MainClass mainClass = null;
ThreadImpl( MainClass mainClass) {
this.mainClass = mainClass;
}
@Override
public void run() {
try {
mainClass.printMyName();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class ThreadImpl2 extends Thread
{
MainClass mainClass = null;
ThreadImpl2(MainClass mainClass) {
this.mainClass = mainClass;
}
@Override
public void run() {
try {
mainClass.printMyName2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The synchronization blocks are on two different variables. One of them is local and another one is an instance variable of MainClass.
My question is even if the synchronization is performed on two different kind of variables. Why "thread2" is put on a waiting state until thread1 finishes the operation?
I have verified the output. This is the output:
Inside printMyName() Sibendu Inside printMyName2() Sibendu
Upvotes: 0
Views: 95
Reputation: 2979
The reason is that you synchronize on String literals, which are in fact the same variable: "Sibendu" == "Sibendu"
.
Therefore, despite the appearances, you use only 1 lock.
String.intern() documentation says:
All literal strings and string-valued constant expressions are interned.
If you replace one of them by name = new String("Sibendu")
, you'll observe the behavior you expected.
Upvotes: 3