【发布时间】:2018-07-28 11:14:08
【问题描述】:
我知道我可以使用可调用对象来获取返回值,但是不使用它是否可以解决这个问题?
我正在尝试从 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;
}
【问题讨论】:
-
嗯,可以肯定,但你为什么要这样做?
Future和Callable为您解决了线程安全问题,如果您不使用它们,则必须自己实现线程安全代码。 -
你能告诉我如何解决这个问题吗?我知道使用 future 和 callable 是最好的,但我想知道为什么我不能在这种特殊情况下调用我的 getter
-
因为您将
tempThread声明为Thread,而getCounter()是primeThread的成员。 -
同样是线程安全的
threadCounter需要声明为volatile。你的程序(通常)会给出正确的答案,但不会通过嗅探测试。 -
哇,我不敢相信我没有看到它。非常感谢你不遗余力地帮助我:)
标签: java multithreading methods compiler-errors runnable