java thread start 前后_java – 为什么再次调用Thread.start时会发生...

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值