java - 为什么线程执行在下一行执行之前就完成了 [英] java - Why the thread execution was finished before the next line was executed
问题描述
我正在一个新线程中编写一个简单的算法.我想知道为什么后面的代码要等到线程完成才能运行.这是一个执行相同操作的简单程序.
I am writing a simple algorithm in a new thread. I wonder why the code that follows waits until the thread is finished in order to run. Here is a simple program that does the same.
public static void main(String[] args) {
final String[] strings = new String[10];
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
strings[i] = String.valueOf(i);
Thread.sleep(10000); // in real code this is wrapped in a simple try catch
}
}
}).run();
for (String string : strings) {
System.out.print(string);
}
}
线程休眠 10 秒,但最后一次迭代是在线程运行完成后执行的.
我什至可以延长睡眠时间.但下一行(最后一次迭代)在线程完成之前不会执行.
这是为什么?
The thread sleeps 10 seconds and yet the last iteration was executed after the thread finished running.
I can even extend the sleep time. but the next line (the final iteration) is not executed until the thread finished.
Why is that?
结果是0 1 2 3 4 5 6 7 8 9
The result is 0 1 2 3 4 5 6 7 8 9
推荐答案
您不会产生线程,因为您只是直接调用 run
方法.您需要改为调用 start
方法.
You are not spawning a thread as you just call run
method directly. You need to call start
method instead.
当您调用start
方法时,JVM 会产生一个新线程并调用Runnable
对象的run
方法.直接调用run
方法和调用其他普通方法类似,没有新线程.
When you call start
method, JVM spawns a new thread and calls the run
method of the Runnable
object. Calling run
method directly is similar to calling any other normal method, no new thread.
这篇关于java - 为什么线程执行在下一行执行之前就完成了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!