【问题标题】:Java Runnable Interface Solution [closed]Java可运行接口解决方案[关闭]
【发布时间】:2019-10-05 14:11:18
【问题描述】:

谁能解释一下下面的代码

public class TestThread implements Runnable {

    public static void main(String[] args) {
        Thread thread = new Thread(new TestThread());
        thread.start();
        System.out.println("1");
        thread.run();
        System.out.println("2");

    }

    @Override
    public void run() {
        System.out.println("3");
    }
}

输出结果为 1 3 3 2。请有人解释一下。

提前致谢

【问题讨论】:

  • 看Java多线程基础就好了。
  • 您还期待什么其他结果?为什么?

标签: java multithreading


【解决方案1】:

当你调用thread.start()方法时,run()方法里面的代码会在一个新线程上执行(因为TestThread类实现了Runnable)。

当您调用 thread.run() 时,这是从主线程中调用 run() 方法,而不是您之前启动的那个。这基本上没有使用任何线程功能。

一旦这个 run() 函数从主线程完成,它就会退出这个函数并到达 println("2") 行。

看起来很直观,因为您在 println("1") 之前调用了 thread.start(),它应该打印 "3 1 3 2",但是,由于多线程的复杂性,不能保证任何顺序这是实施的方式。它可以根据多种因素打印“1 3 3 2”或“3 1 3 2”。

您可以尝试的一个实验是让打印语句包含调用它们的线程的名称。

public class TestThread implements Runnable {

    public static void main(String[] args) {
        Thread thread = new Thread(new TestThread(), "newThread");
        thread.start();
        System.out.println(Thread.currentThread().getName() + ": 1");
        thread.run();
        System.out.println(Thread.currentThread().getName() + ": 2");
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": 3");
    }
}

对我来说,这个输出:

main: 1
main: 3
newThread: 3
main: 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多