Ans: If two threads work on the same instance,second thread needs to wait till first thread completes execution.If threads are working on different instance,two threads will execute independently irrespective of other thread.If you declare methods as static,it will be like working on same copy.
example :
public class A {
public synchronized void methodA() throws InterruptedException {
System.out.println("entered into A");
Thread.sleep(10000l);
System.out.println("after sleeping into A");
}
public synchronized void methodB() throws InterruptedException {
System.out.println("entered into B");
Thread.sleep(10000l);
System.out.println("after sleeping into B");
}
}
public class aTest {
public static void main(String[] args) throws InterruptedException {
final A ain = new A();
final A bin = new A();
Runnable r1 = new Runnable() {
public void run() {
try {
ain.methodA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable r2 = new Runnable() {
public void run() {
try {
bin.methodB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
t1.join();
t2.join();
}
}
entered into A
entered into B
after sleeping into A
after sleeping into B
If methods are static or accessing methods with ain instance only,then o/p:
entered into A
after sleeping into A
entered into B
after sleeping into B
What is the difference when the synchronized keyword is applied to a static method or to a non static method?
Ans) When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class donĂ¢€™t interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but canĂ¢€™t access the synch non static method.
No comments:
Post a Comment