我知道我可以使用可调用对象来获取返回值,但是不使用它就可以解决这个问题吗?
我正在尝试从primeThread获取tempCounter值,并将它们全部添加到计数器中。但是我收到“找不到符号”错误。
我可以从PrimeCounter类的arrayList调用runnable方法吗?
public class PrimeCounter {
public static void countPrimes() {
int counter = 0;
int primeNumbers = 2_534_111;
final int NUM_OF_THREAD = 4;
int startRange = 2;
int range = primeNumbers / NUM_OF_THREAD;
int endRange = startRange + range;
ArrayList<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < NUM_OF_THREAD; i++) {
threadList.add(new Thread(new primeThread(startRange, endRange)));
startRange += range;
if (endRange + range < primeNumbers) {
endRange += range;
} else {
endRange = primeNumbers;
}
}
for (Thread t : threadList) {
t.start();
try {
t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
for (int i = 0; i < threadList.size(); i++) {
Thread tempThread = threadList.get(i);
while (tempThread.isAlive()) {
counter += tempThread.getCounter(); // symbol not found
}
}
System.out.println("\nNumber of identified primes from 2 to " + primeNumbers + " is :" + counter);
}
// checks if n is a prime number. returns true if so, false otherwise
public static boolean isPrime(long n) {
//check if n is a multiple of 2
if (n % 2 == 0) {
return false;
}
//if not, then just check the odds
for (long i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
primeThread可运行
class primeThread implements Runnable {
private int startRange;
private int endRange;
private int threadCounter = 0;
public primeThread(int startRange, int endRange) {
this.startRange = startRange;
this.endRange = endRange;
}
@Override
public void run() {
for (int i = startRange; i < endRange; i++) {
if (Dumb.isPrime(i)) {
threadCounter++;
}
}
}
public int getCounter() {
return threadCounter;
}
最佳答案
首先阅读有关Java naming convention的信息(您的类名不符合约定)
使用这个片段,您说每个线程都要启动,然后在下一个步骤启动主线程之前等待该线程的终止(您真的要这样吗?):
for (Thread t : threadList) {
t.start();
try {
t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
最后,您从arrayList获得了一个线程,然后尝试运行该线程所没有的方法。
for (int i = 0; i < threadList.size(); i++) {
Thread tempThread = threadList.get(i);
while (tempThread.isAlive()) {
counter += tempThread.getCounter(); // symbol not found
}
}
getCounter是primeThread类的方法,但是您有Thread类!
如果您的类 primeThread扩展了Thread类,则可以解决此问题。