18软一003 2019-12-26 10:40 采纳率: 0%
浏览 178

java多线程,关于join()执行顺序问题。

在执行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.");
    }
}![图片说明](https://img-ask.csdn.net/upload/201912/26/1577328013_682091.png)


  • 写回答

1条回答 默认 最新

  • 关注
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题