I have two methods in a class and one is synchronized and other one is non-synchronized. When I am calling these methods with two different threads , I am seeing the execution becomes serial not parallel .
I am confused , as per theory r.processSomething() should not wait for r.doSomething() to complete its execution.
If anyone has some idea on executing two methods(synchronized and non-synchronized) simultaneously. Please share.
class LockObjectDemo{
public static void main(String[] args){
SharedResource r = new SharedResource();
MyThread t1 = new MyThread(r);
t1.start();
MyThread t2 = new MyThread(r);
t2.start();
}
}
class MyThread extends Thread{
private SharedResource r ;
MyThread(SharedResource r){
this.r = r;
}
public void run() {
try {
r.doSomething(); // Only after completing this method , the other thread enters into the next method which is not locked
r.processSomething();
} catch(Exception ex){
System.out.println(ex);
}
}
}
class SharedResource{
public void doSomething() throws Exception{
synchronized(this){
System.out.println("Doing Something -> "+Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println("Done Something->"+Thread.currentThread().getName());
}
}
public void processSomething() throws Exception{
System.out.println("Processing Something -> "+Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("Done Processing->"+Thread.currentThread().getName());
}
}