I have following program in same file. I have synchronized the run() method.
class MyThread2 implements Runnable {
Thread t;
MyThread2(String s)
synchronized
methods work at the instance level. Each instance of the class gets its own lock. The lock gets acquired every time any synchronized
method of the instance is entered. This prevents multiple threads calling synchronized
methods on the same instance (note that this also prevents different synchronized
methods from getting called on the same instance).
Now, since you have two instances of your class, each instance gets its own lock. There's nothing to prevent the two threads each operating on its own instance concurrently.
If you do want to prevent this, you could have a synchronized(obj)
block inside run()
, where obj
would be some object shared by both instances of your class:
class MyThread2 implements Runnable {
private static final Object lock = new Object();
...
public void run() {
synchronized(lock) {
...
}
}
}