I tried to make start, N final then, initialize them, then use lock for primes[total], total, but however Netbeans keep showing error that start, N is not initialized, so the problem is how to initialize final variables? (There is also main method but I havnt posted to keep the question short)
public class PrimeBuggy implements Runnable {
//private static int start, N;
//I changed above line to following:
private final int start,N;
private static int numThreads;
private static int primes[];
private static boolean pflag[];
private static int total = 0;
//I created a lock
private Lock lock();
this.start = start;
this.N = N;
private static boolean is_prime(int v) {
int i;
int bound = (int)Math.floor(Math.sqrt((double)v)) + 1;
for (i = 2; i < bound; i++) {
if (pflag[i])
continue;
if (v % i == 0) {
pflag[v] = true;
return false;
}
}
return (v > 1);
}
/***/
private int threadNum;
private PrimeBuggy(int threadNum) { this.threadNum = threadNum; }
public void run() {
int i;
//lock this begining
lock.lock();
start = N/numThreads * threadNum;
N = start + N/numThreads;
for (i = start; i < N; i++) {
if (is_prime(i)) {
primes[total] = i;
total++;
//unlock at the end
lock.unlock();
}
}
}
if a field is final, then you have to initialize it when it's declared or with a constructor:
private final int N =10;
private PrimeBuggy(int threadNum) {
start = N/numThreads * threadNum;
this.threadNum = threadNum;
}
Nevertheless, you have in your code several initialization in a methid:
start = N/numThreads * threadNum;
N = start + N/numThreads;
and this makes no sense at all:
//I created a lock
private Lock lock();
this.start = start;
this.N = N;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.