【发布时间】:2013-09-26 20:22:49
【问题描述】:
我有一个函数,其输出由多个线程处理(在函数调用发生后创建)。但是当我运行程序时,我会在函数完成运行之前从线程收到 NullPointerException。如何指定 Java 不提前启动线程?
public class MainThread extends Thread {
public MainClass() {
...
myRunnable1 = new myRunnable(args[]);
myRunnable2 = new myRunnable(args[]);
...
}
public void run() {
for (someNumberOfRuns) {
function1();
System.out.println("Done");
thread1 = new Thread(myRunnable);
thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();
...
}
}
}
在 for 循环的第一次迭代中,thread1 和 thread2 都会抛出 NullPointException 错误,然后系统将打印出“Done”。有谁知道为什么这两个线程在方法中各自的 start() 调用之前启动? 谢谢。 (Java版本为1.6u26)
【问题讨论】:
-
请张贴实际的相关代码和你如何运行它的例子,即。带参数。
-
> "for (someNumberOfRuns) {" 不解析为 Java 代码。请再试一次。
-
不要扩展 Thread,而应该实现 Runnable 以避免混淆。你能发布编译和演示问题的真实代码吗?
-
并反馈我的回答。如果对你有帮助,记得接受。
标签: java multithreading runnable