Reputation: 289
As documentation says
while sleeping a Thread does not release the locks it holds
However my code snippet demonstrates it does release the lock
public class SynchronizationTest {
public static void main(String[] args) {
Common c = new Common();
new PersonONE(c);
new PersonTWO(c);
}
}
class Common {
private String message = "This is shared message";
public String getMessage() {
return message;
}
}
class PersonONE extends Thread {
private Common c;
public PersonONE(Common c) {
this.c = c;
start();
}
@Override
public void run() {
synchronized (c.getClass()) {
for (int i = 0; i < 5; i++) {
System.out.println("PersonONE: " + c.getMessage());
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {}
}
}
}
}
class PersonTWO extends Thread {
private Common c;
public PersonTWO(Common c) {
this.c = c;
start();
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("PersonTWO: "+c.getMessage());
try {
Thread.sleep(100);
} catch (InterruptedException e){}
}
}
}
Output
PersonONE: This is shared message
PersonTWO: This is shared message
PersonONE: This is shared message
PersonTWO: This is shared message
PersonONE: This is shared message
PersonTWO: This is shared message
PersonONE: This is shared message
PersonTWO: This is shared message
PersonONE: This is shared message
PersonTWO: This is shared message
So, the question is: where am I wrong ?
Upvotes: 0
Views: 596
Reputation: 5546
PersonTWO doesn't try to acquire the lock.
See below for an example that does demonstrate that sleeping does not release a lock.
private static class Locker implements Runnable {
private final Object lock;
private final String message;
private Locker(final Object lock, final String message) {
this.lock = lock;
this.message = message;
}
@Override
public void run() {
try {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
System.out.println(message);
Thread.sleep(1000);
}
}
}
catch (InterruptedException ex) {
}
}
}
public static void main(String[] args) {
final int numThreads = 2;
final Object lock = new Object();
for (int i=0;i<numThreads;i++) {
new Thread(new Locker(lock, "Hello - " + i)).start();
}
}
Upvotes: 6