android - "new Thread"没有启动新线程?

标签 android multithreading runnable

我想在执行 new Thread 行时启动一个新线程。我是这样做的:

new Thread ( new Runnable() {

@Override
    public void run() {

            .....
    }
}).start();

//other code continues here

当代码到达新的线程行时,它会跳转到执行其他代码。为什么?

最佳答案

因为新线程几乎立即开始运行,并且新线程声明之后的代码正在由同一个先前线程执行。

这是正在发生的事情:

// Main thread running

// Some random code...

new Thread ( new Runnable() {
@Override
public void run() {
    // This code will run in another thread. Usually as soon as start() gets called!
}
}).start();

// This code is still being executed by the main thread.

除了附加调试器之外,检查线程是否真正开始运行的一种简单方法是在 run() 中放置一个 Log 语句

关于android - "new Thread"没有启动新线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45612984/

相关文章:

android - savedInstanceState.getInt 中的第二个参数是什么?

Android 异步任务与 native Java 线程

java - 使用 System.out.format 和 System.out.println 进行多线程

c++ - std::thread::join 是否保证写入可见性

java - 无法在 android 中打开 URLConnection

android - 使用 lambda forEach Kotlin 遍历列表

c# - 将对象的引用传递给新线程

java - 实例变量无法识别为 "this"w/in Runnable

Java GUI与串口通信

java - 我应该使用 Executor 只运行 1 个 Runnable 吗?何时使用执行者?