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

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.");
    }
}
  • 写回答

1条回答 默认 最新

  • 宾灬 2019-12-26 11:53
    关注

    因为你两个线程都start了,当然会运行,跟join没关系。first.join()意思是当前线程阻塞,直到first线程完成。

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100