gpt4 book ai didi

java - 线程无缘无故给出 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 10:18:19 25 4
gpt4 key购买 nike

所以我正在做这个笨拙的例子来理解 Java 中的线程是如何工作的。实际上这很简单,但是,我似乎不明白为什么当它尝试触发超过 3 个线程时会给我一个 NullPointerException 异常。

你能解决吗? Eclipse 的调试器没有帮助:-(

提前致谢!!

public class Main {

public static void main(String[] args) {

Main boot = new Main();
}

public Main()
{
CoolThread myThread = new CoolThread(1, 2);
Thread t_myThread = new Thread(myThread);
t_myThread.start();

myThread.defineMain(this);
}


public void teste(String tests){
CoolThread myThread = new CoolThread(1, 2);
Thread t_myThread = new Thread(myThread);
t_myThread.start();
}

}

public class CoolThread extends Thread {

int firstNum;
int secondNum;
Main myMain;

/**
* Constructor
* @param firstNum
* @param secondNum
*/
public CoolThread(int firstNum, int secondNum)
{
this.firstNum = firstNum;
this.secondNum = secondNum;
}

public void defineMain(Main myMain)
{
this.myMain = myMain;
}
/**
* Fires the thread.
*/
public void run()
{
try{
int number = 0;
for(;;)
{

int soma = (firstNum+secondNum);
System.out.println("ID: " +Thread.currentThread().getId());
firstNum++;
secondNum++;
number++;
Thread.sleep(100);
if((number % 10) == 0)
{
myMain.teste("The sum is: " + soma);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}

}

}

顺便说一句,这是我得到的输出:

ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 12
ID: 9
ID: 12
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 9
ID: 12
ID: 9
ID: 14
java.lang.NullPointerException
at my.own.package.CoolThread.run(CoolThread.java:44)
at java.lang.Thread.run(Thread.java:722)

它继续创建和终止线程...

最佳答案

您要么调用 myThread.defineMain(...) 启动您的线程(在 Main 中),要么不调用 defineMain(...) 完全没有(在 teste(...) 中)。您需要在线程运行之前定义 main ,否则当您到达第 44 行时 myMain 有可能是 null 我假设是:

myMain.teste("The sum is: " + soma);

这是一个 thread race condition 的定义.您的开始代码应该是:

CoolThread myThread = new CoolThread(1, 2);
// this must be done _before_ the thread starts below
myThread.defineMain(this);
Thread t_myThread = new Thread(myThread);
t_myThread.start();

永远不要认为 JDK 是错误的。这只会扼杀你用来发现问题的任何调试和批判性思维。了解如何 use the debugger in eclipse .然后,您可以在第 44 行放置一个断点并调查变量。

不幸的是,在这种情况下,您有一个线程程序,调试正在改变程序的时间,很可能隐藏了错误。您可能已经尝试在第 44 行打印出各种对象以查看哪个是 null


此外,正如@kurtzbot 指出的那样,如果 CoolThread 扩展 Thread 那么你可以说 new CoolThread() 然后 coolThread.start()。实际上,您应该做的是让 CoolThread 实现 Runnable 而不是扩展 Thread。这是更好的模式:

CoolThread myThread = new CoolThread(1, 2);
// this must be done _before_ the thread starts below
myThread.defineMain(this);
Thread t_myThread = new Thread(myThread);
t_myThread.start();
...

public class CoolThread implements Runnable {
public void run() {
...
}
}

关于java - 线程无缘无故给出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12046302/

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