public class MainClass { public static void main(String[] args) {
T1 ok = new T1();
T2 ok1 = new T2();
ok.start();
ok1.start();
}
}
public class T1 extends Thread {
@Override
public void run() {
DemoClass q = new DemoClass();
for (int i = 0; i <= 5; i )
try {
q.demoMethod();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class T2 extends Thread {
@Override
public void run() {
DemoClass q = new DemoClass();
for (int i = 0; i <= 5; i )
try {
q.demoMethod1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class DemoClass {
String s = "";
String s1 = "";
public void demoMethod() throws InterruptedException {
System.out.println(Thread.currentThread().getName() " Entered m1");
synchronized (s) {
System.out.println(Thread.currentThread().getName() " Inside m1 ");
Thread.sleep(5000);
}
System.out.println(Thread.currentThread().getName() " m1");
}
public void demoMethod1() throws InterruptedException {
System.out.println(Thread.currentThread().getName() " Entered m2");
System.out.println(Thread.currentThread().getName() " Inside m2 ");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() " m2");
}
}
Even when I created separate objects of DemoClass, then called separate methods through separate threads. why does only one thread work at one time?
Or if someone can suggest which type of locking will we call for the code in DemoClass
CodePudding user response:
You're synchronizing on s
, which is always the same object.
Don't do that. Synchronize on this
if you're going to synchronize on anything.