This question might be duplicated, so please tell me if it's true.
I'm trying to understand synchronization in Java, but it's not clear to me that 'When to use wait()
method in Object class.
Let's say I have simple class as below.
class Test {
static class Example {
int value = 0;
public synchronized void increment() {
value++;
}
}
public static void main(String[] args) throws InterruptedException {
Example example = new Example();
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> example.increment());
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(example.value);
}
}
10 threads try to invoke increment
method which is synchronized. This works well, but the curious thing is that I've never called notify()
method in increment()
method. If a thread 'X' enters synchronized block with monitor(mutex), then other threads would be blocked and wait for signal from 'X' thread, isn't it ? But how is it possible ?
Is the compiler adding a function at the end of the code ? (But when I added calling wait()
method without notify()
method, it didn't work well) What is happening in my code?
Update
Let's say I add a condition that threads should increase value only if thread number is equal to current thread number
class Test {
static class Example {
int value = 0;
@SneakyThrows
public synchronized void increment() {
String name = Thread.currentThread().getName();
int threadNumber = name.charAt(name.length() - 1) - 48;
while (threadNumber != value) {
System.out.println(threadNumber + " : release");
wait();
}
value++;
System.out.println(threadNumber + " notify");
notifyAll();
}
}
public static void main(String[] args) throws InterruptedException {
Example example = new Example();
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> example.increment());
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(example.value);
}
}
In this case, when I delete notifyAll()
method, it never ends. So, I thought that "notify() method is not executed after exit of synchronized block". Is this right?