这个问题在这里已有答案:
import java.io.*;
class threads extends Thread{
int counter=0;
static volatile boolean counting=true;
public void run(){
if(counting) {
counter++;
}
}
}
public class cores {
static PrintWriter pw= new PrintWriter(System.out, true);
@SuppressWarnings({ "static-access", "deprecation" })
public static void main(String args[]) throws InterruptedException {
int mastercounter=0;
Thread mainthread=Thread.currentThread();
int cores= Runtime.getRuntime().availableProcessors();
threads[] array=new threads[cores];
for (int x=0;x<cores;x++) {
threads t=array[x];
t.start();
}
mainthread.sleep(5000);
threads.counting=false;
for (int x=0;x<cores;x++) {
threads t=array[x];
t.stop();
mastercounter+=t.counter;
}
pw.println(mastercounter);
}
上面的代码是我尝试一个简单的基准测试程序,它试图通过简单地使用5秒内可能计算的所有线程来利用计算机CPU上的所有可用内核。
代码在NullPointerException
行上给出了一个t.start()
,我假设这是因为我试图解决的方法是无法动态命名变量。
任何建议,修复或提示都非常感谢。
threads[] array=new threads[cores];
你创建了一个从未赋值的threads
类型的新数组,因为threads
是一个类,数组本身就是一个包含引用的数组。当您调用时,引用数组的默认值为null
:
t.start();
你在start()
值上调用null
方法,因此你得到NullPointerException
。您需要在为其分配值并在这些值上调用方法之前初始化数组。
你的数组没有元素。 threads t=array[x];
当然是空的。
尝试制作一些对象,请将您的课程资本化
array[x] = new Threads();
array[x].start();