我想在执行new Thread
的行时开始一个新的线程。我这样做:“新线程”不启动新线程?
new Thread (new Runnable() {
@Override
public void run() {
.....
}
}).start();
//other code continues here
当代码来到新的线程行它跳转到执行其他代码。为什么?
我想在执行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.
除了安装调试器,一个简单的方法来检查线程是否真正开始运行的方法是把Log
语句中run()
如何检查在与主线程“并行”的另一个线程中运行的执行代码?我在run()的第一行代码中放了一个断点,但它没有执行。 – Zobi
你什么时候放置断点?之前运行您的应用程序或之后? –
@Zobi做了一件事,在run()方法中加入一个日志并检查它是否正在执行 –
它稍后将在'run()'内执行代码。 – azizbekian
因为您可能正在调试启动新线程的线程。如果你在'run()'方法中放置了一个logline或者一个断点,你会发现它被执行了 – 0xDEADC0DE
@ 0xDEADCODE我在run方法的第一行代码中放置了一个断点......当我调试它时仍然转到其他代码行。 – Zobi