gpt4 book ai didi

java - Eclipse 调试器不适用于这两个小线程

转载 作者:行者123 更新时间:2023-12-01 17:24:40 26 4
gpt4 key购买 nike

如何调试这个?我知道这不是线程安全的,但只是想跟踪逻辑。

class Test {
public static int count = 0;
class CountThread extends Thread {

public void run()
{
System.out.println(Thread.currentThread().getName() + " start");
count++;
System.out.println(Thread.currentThread().getName() + " end");
}
}

public void add(){
CountThread a = new CountThread();
CountThread b = new CountThread();

a.start();
b.start();

try {
a.join();
b.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}

}
public static void main(String[] args) {

Test test = new Test();
System.out.println("START = " + Test.count);

test.add();

System.out.println("END: Account balance = " + Test.count);
}

当执行到a.start()时,在Eclipse中我点击“step into”,它没有进入run()方法,而是进入下面,并且没有办法进入run()在我的代码中。如何调试这个?

     public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0 || this != me)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}

最佳答案

When it's executed to a.start(), in Eclipse I click "step into", it doesn't go to the run() method, but go to [the Thread.start() method], and there is no way to go to run() in my code.

这是可以预料到的,并不是 Eclipse 的问题。您无法调试线程 fork 并开始执行时正在执行的 native 方法。

How to debug this?

我会在 run() 方法的第一行放置一个断点。或者,如果必须的话,您可以在调用 run() 方法的 Thread.run() 方法中放置一个断点:

// the Thread.run() method
public void run() {
if (target != null) {
// Your `CountThread` objects are the `target`.
target.run();
}
}

注意:您需要了解,此类程序的任何调试都将极大地改变线程的执行顺序。 System.out.println() 调用也会执行此操作,因为它们会产生 IO,并且底层 PrintStream同步的。这意味着一旦删除打印语句和断点,您的程序的行为将会非常不同。

关于java - Eclipse 调试器不适用于这两个小线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com