how could I kill or stop the thread each time, to get around this problem?
答案是,你做不到.一旦启动,线程可能无法重新启动.在javadoc for Thread中清楚地记录了这一点.相反,你真正想做的是每次循环时都使用RemoveNonPrime的新实例.
您的代码中还有其他一些问题.
首先,您需要在再次使用之前递增p:
for(int i = 0; i < cores; i++){
t[i] = new removeNonPrime(f,p); //
}
其次,您可能是多线程的,但您不是并发的.您拥有的代码基本上只允许一次运行一个线程:
while(p <= (int)(Math.sqrt(N))){
t[p%cores].start();//
try{
t[p%cores].join(); //
}catch(Exception e){}
//get the next prime
p++;
while(p<=(int)(Math.sqrt(N))&&f[p]==0)p++;
}
只是我的0.02美元,但你想要做的可能会工作,但选择下一个最小素数的逻辑并不总是选择素数,例如,如果其他线程中的一个尚未处理该数组的那部分.
以下是使用ExecutorService的方法,您需要填写一些空白(…):
/* A queue to trick the executor into blocking until a Thread is available when offer is called */
public class SpecialSyncQueue extends SynchronousQueue {
@Override
public boolean offer(E e) {
try {
put(e);
return true;
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
}
ExecutorService executor = new ThreadPoolExecutor(cores, cores, new SpecialSyncQueue(), ...);
void pruneNonPrimes() {
//...
while(p <= (int)(Math.sqrt(N))) {
executor.execute(new RemoveNonPrime(f, p));
//get the next prime
p++;
while(p<=(int)(Math.sqrt(N))&&f[p]==0)p++;
}
//count primes
int total = 0;
System.out.println();
for(int j=0; j
if(f[j]!=0){
total++;
}
}
System.out.printf("Number of primes up to %d = %d",f.length,total);
}
class RemoveNonPrime extends Runnable {
int k;
int arr[];
public RemoveNonPrime(int arr[], int k){
this.arr = arr;
this.k = k;
}
public void run(){
int j = k*k;
while(j
if(arr[j]%k == 0)arr[j]=0;
j+=k;
}
}
}