gpt4 book ai didi

java - 为什么多线程 Java 代码的行为与单线程类似?

转载 作者:行者123 更新时间:2023-12-01 18:18:46 25 4
gpt4 key购买 nike

我希望在第一行打印出以下代码:初始值。

public class RunnableLambda {

static String accessedByThreads = "initial value";

public static void main(String... args) {
Runnable r8 = () -> {
try {
Thread.currentThread().sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("r8");
accessedByThreads = "from runnable lambda";
};
r8.run();
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("r");
accessedByThreads = "from runnable anonymous";
}
};
r.run();
System.out.println("Main");
System.out.println(accessedByThreads);
}
}

因为我希望生成的线程在主线程之后完成。但是,它在最后一行打印出:来自可运行的匿名。

为什么?

最佳答案

Runnable.run() 不会启动新线程。这是一个正常的方法调用,就像在任何其他对象上一样。您需要调用Thread.start()方法创建一个新线程。

您需要编写而不是r8.run();

Thread t1 = new Thread (r8);
t1.start(); //this creates and runs the new thread in parallel

r.run();使用相同:

Thread t2 = new Thread (r);
t2.start();

关于java - 为什么多线程 Java 代码的行为与单线程类似?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28153837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com