[英]Why is Non blocking asynchronous single-threaded faster for IO than blocking multi-threaded for some applications
[英]Why is multi-threaded Java code behaving like single-threaded?
我希望下面的代碼在第一行打印出來:初始值。
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();
相同r.run();
采用:
Thread t2 = new Thread (r);
t2.start();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.