Reputation: 1793
I have written the below Java program. This program is creating three threads and started them all :
public class MyThread implements Runnable {
@Override
public synchronized void run() {
int count = 0;
while (true) {
System.out.println("" + Thread.currentThread().getName());
if (count == 20 && Thread.currentThread().getName().equals("Thread-1")) {
try {
Thread.currentThread().sleep(100000000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
count++;
}//while ennds here
}//run ends here
}//class ends here
public class TestThread {
public static void main(String[] args){
Thread t1 = new Thread(new MyThread());
t1.setName("Thread 1");
Thread t2 = new Thread(new MyThread());
t1.setName("Thread 2");
Thread t3 = new Thread(new MyThread());
t1.setName("Thread 3");
t1.start();
t2.start();
t3.start();
}
}
Second thread goes on sleep after some time.
As the run method is synchronized, it is supposed to be accessed only by one thread at a time.
Sleep method never releases the lock on the object. But here once the "Thread 1" goes to sleep, after that "Thread 2" and "Thread 3" are successfully able to access the same method and continue there execution.
Can anybody explain that what is happening here ? execution should be on hold after "Thread 1" goes on sleep according to the concept of sleep.
Upvotes: 0
Views: 128
Reputation: 249
If you want have synchronization for all threads you need to use some static field. It could be monitor (simple Object used with synchronization) or Lock
private static final Lock LOCK = new ReentrantLock();
@Override
public void run() {
try {
LOCK.lock();
// Your code
} finally {
LOCK.unlock();
}
Upvotes: -1
Reputation: 280168
Your synchronized
is on an instance method. It will only be synchronized
if you were calling the method on the same instance. You aren't doing that. You're calling the run()
method on 3 different instances.
Upvotes: 3