所以我正在做这个尴尬的例子来了解 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)
它继续创建和杀死线程......