Reputation: 13
for (int i = 0; i < 3; i++) {
list.add("test" + i);
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (list) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("test3");
}
}
});
thread.start();
synchronized (list) {
System.out.println(list);
}
What I'm not understanding right now is, the printout doesn't contain "test3". Shouldn't synchronizing list during the thread halt the println at the end?
So they should be in order of:
Thread.sleep();
list.add("test3");
println(list);
What's going on?
Upvotes: 0
Views: 65
Reputation: 2981
What I'm not understanding right now is, the printout doesn't contain "test3". Shouldn't synchronizing list during the thread halt the println at the end?
That would imply that the Thread you started would get the lock before the main thread. There is no way to guarantee that in Java. In fact, it seemed to work the other way round, main thread takes lock before the second thread, blocking the second thread from taking the lock.
You could try to use the wait/notify mechanism to ensure the main thread is waiting for the other thread to terminate: import java.util.ArrayList;
for (int i = 0; i < 3; i++) {
list.add("test" + i);
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (list) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("test3");
// Notify the main thread
list.notify();
}
}
});
thread.start();
synchronized (list) {
try {
// wait for the other thread for a specified time to terminate
// this will temporary release the lock for the second thread.
list.wait(5000);
} catch (InterruptedException e) {
// see above..
e.printStackTrace();
}
System.out.println(list);
}
Upvotes: 0
Reputation: 393916
Shouldn't synchronizing list during the thread halt the println at the end?
That would only be true if the second thread's run()
method's execution (and in particular the execution of the synchronized (list)
statement within it) started before the synchronized (list)
statement of the main thread is executed.
Calling thread.start();
before synchronized (list) {System.out.println(list);}
does not guarantee the second thread will start running before synchronized (list) {System.out.println(list);}
is executed.
Upvotes: 3