在执行main函数的first.join();时,为何两个线程都运行了
运行截图如下
代码如下:
public class Main {
void f() {
FirstThread first = new FirstThread(this);
SecondThread second = new SecondThread(this);
first.start();
second.start();
try {
System.out.println("Waiting for first thread to finish...");
first.join();
System.out.println("It's a long wait!");
System.out.println("Waking up second thread..");
synchronized (this) {
this.notify();
}
System.out.println("Waiting for second thread to finish..");
second.join();
} catch (InterruptedException e) {
}
System.out.println("I'm ready to finish too.");
}
public static void main(String[] args) {
Main m = new Main();
m.f();
}
}
class FirstThread extends Thread {
Object lock;
FirstThread(Object o) { lock = o; }
public void run() {
try {
System.out.println("First thread starts running.");
sleep(10000);
System.out.println("First thread finishes running.");
} catch (InterruptedException e) {
}
}
}
class SecondThread extends Thread {
Object lock;
SecondThread(Object o) { lock = o; }
public void run() {
System.out.println("Second thread starts running.");
System.out.println("Second thread suspend itself.");
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e) {
}
System.out.println("Second thread runs again and finishes.");
}
}