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 Fluent udf 编写问题
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500
  • ¥15 氧化掩蔽层与注入条件关系
  • ¥15 Django DRF 如何反序列化得到Python对象类型数据
  • ¥15 多数据源与Hystrix的冲突