“新线程”没有启动新线程?

时间:2017-08-10 11:51:44

标签: android multithreading runnable

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

new Thread ( new Runnable() {

@Override
    public void run() {

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

//other code continues here

当代码进入新线程时,它会跳转以执行其他代码。为什么呢?

2 个答案:

答案 0 :(得分:3)

好吧,因为新线程几乎立即开始运行,新线程声明后面的代码正由同一个前一个线程执行。

这就是发生的事情:

// 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.

除了附加调试器之外,检查线程是否真正开始运行的简单方法是在Log

中放置run()语句

答案 1 :(得分:0)

简单:因为你想要发生的事情发生了!

您使用 new()创建新主题,并且因为您立即在该对象上调用 start(),该作业将开始执行 >工作。

你的主线程继续其“主要”工作。这就像:你拍拍你的朋友(告诉他:开始跑步) - 现在你问:“他为什么离开?”

这就是全部!