class Isprimer implements Runnable
{
private int count=0;
private int start,end;
public Isprimer(int n,int m){
start=n;
end=m;
}
public synchronized void check(){
for(int i=start;i<end;i++){
int k=(int) Math.sqrt(i);
for(int j=2;j<k;j++){
if(i%j==0)break;
}
if(i>=k+1)count++;
}
}
public int get_num(){
return count;
}
public void run(){
this.check();
}
}
public class app14_20 { public static void main(String[] args) {
Isprimer a1=new Isprimer(2,10000);
Isprimer a2=new Isprimer(10000,20000);
Thread b1=new Thread(a1);
Thread b2=new Thread(a2);
b1.start();
b2.start();
System.out.println("The primer between 2 and 10000 is: "+a1.get_num());
System.out.println("The primer between 10000 and 20000 is: "+a2.get_num());
}
}

解决方案 »

  1.   


         
       b1.start();
       b2.start();
       while (b1.isAlive()) {
       }
       while (b2.isAlive()) {
       }
    估计你没有等待线程结束,就开始打印结果。所以出错。
    而且你的Check函数好像不对。。哈。
      

  2.   

    我都没看到你的run方法,你在干什么啊???
      

  3.   

        b1.start();
        b2.start();
        try {
          b1.join();
          b2.join();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }增加join, 等待线程结束后再继续运行输出
      

  4.   

    我的建议:在学多线程前先搞清楚多线程的一些机制。
    如独立使用局部变量。sleep,notify,wait,jion这些用法。
    以及在独立处理器上:是宏观并行,微观在时间片上串行。
      

  5.   

    public synchronized void check() {
        for (int i = start; i < end; i++) {
          int k = (int) Math.sqrt(i);
          for (int j = 2; j < k; j++) {
            if (i % j == 0)
              break;
            if(j== k-1)
            count++;
          }    }
      }觉得你check函数不对,可以改成这样,结果是:
    The primer between 2 and 10000 is: 1257The primer between 10000 and 20000 is: 1045
      

  6.   


    换了一下算法,这个算法是最笨的了 int j;
    for(int i=start;i <end;i++){ 
    for(j=2;j <i;j++){ 
    if(i%j==0)
    break; 

    if(j==i)
    count++;