为什么多线程 Java 代码表现得像单线程?
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);
}
}
因为我希望生成的线程在主线程之后完成。但是,它在最后一行打印出来:from runnable anonymous。
为什么?
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();
我希望在第一行打印出以下代码:初始值。
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);
}
}
因为我希望生成的线程在主线程之后完成。但是,它在最后一行打印出来:from runnable anonymous。
为什么?
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();