suppose that thread 1 executes wait (), thread 2 to acquire lock resources, while thread 3 starts to execute synchronized to compete for lock resources, and thread 2 uses notifyAll () to wake up thread 1 before ending, so which thread 1 or thread 3 can acquire the lock at random?
in my understanding, it is random, but now the actual situation is that thread 1 will get the resource
I understand it wrong, please explain.
and after thread 1 executes wait, thread 4 first acquires the lock resource, but also executes wait, and then continues as above, why thread 1 and thread 4 are executed when thread 2 ends.
public class ThreadTest {
public static void main(String[] args) {
Object co = new Object();
System.out.println(co);
for (int i = 0; i < 10; iPP) {
MyThread t = new MyThread("Thread" + i, co);
t.start();
}
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("-----Main Thread notify-----");
synchronized (co) {
co.notify();
}
TimeUnit.SECONDS.sleep(2);
System.out.println("Main Thread is end.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class MyThread extends Thread {
private String name;
private Object co;
public MyThread(String name, Object o) {
this.name = name;
this.co = o;
}
@Override
public void run() {
System.out.println(name + " is waiting.");
try {
synchronized (co) {
co.wait();
}
System.out.println(name + " has been notified.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
for example, this code, regardless of whether it will cause a deadlock, the problem is that the notify released in main must be the first to execute wait, isn"t it random?