为什么多线程Java代码的行为类似于单线程?
我希望在第一行打印出以下代码:初始值为什么多线程Java代码的行为类似于单线程?,java,multithreading,synchronization,Java,Multithreading,Synchronization,我希望在第一行打印出以下代码:初始值 public class RunnableLambda { static String accessedByThreads = "initial value"; public static void main(String... args) { Runnable r8 = () -> { try { Thread.currentThread().sleep(30
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 anonymous
为什么?Runnable.run()
不会启动新线程。这是一个普通的方法调用,就像对任何其他对象一样。您需要调用该方法来创建新线程
而不是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();
Runnable.run()
不会启动新线程。这是一个普通的方法调用,就像对任何其他对象一样。您需要调用该方法来创建新线程
而不是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();
您认为您正在哪里创建其他线程?您只是在两个Runnable
对象上调用run
,而不是启动线程。您只需从Runnable调用方法run()。使用start()可能是Thank you:)的副本(我想知道我喝了什么…)你认为你在哪里创建其他线程?您只是在两个Runnable
对象上调用run
,而不是启动线程。您只需从Runnable调用方法run()。使用start()可能是Thank you:)的副本(我想知道我喝了什么….)