求素数(多线程练习题)

编写一个有两个线程的程序,第一个线程用来计算2~100000之间的素数的个数,

第二个线程用来计算100000~200000之间的素数的个数,最后输出结果。

代码实现:

 

package com.thread;

public class SuShuDemo1 extends Thread{
    private long suCount = 0;
    public boolean flag = false;

    public long getSuCount() {
        return suCount;
    }

    @Override
    public void run() {

        for (long i=2;i<=100000;i++){
            for (long j=2;j<=Math.sqrt(i);j++){
                if (i%j==0){
                    flag=true;
                    break;
                }
            }

            if (flag==false){
                this.suCount++;
            }

            flag=false;
        }
        System.out.println(Thread.currentThread().getName()+"素数一共有"+getSuCount()+"个");
    }
}

 

  

package com.thread;

public class SuShuDemo2 implements Runnable {
    private long suShuCount2 = 0;

    public long getSuShuCount2() {
        return suShuCount2;
    }

    @Override
    public void run() {
        for (long i =100000;i<=200000;i++){
            long j =0;
            for (j =2;j<=i;j++){
                if (i%j==0){
                    break;
                }
            }
            if (i==j){
                this.suShuCount2++;
            }
        }
        System.out.println(Thread.currentThread().getName()+"素数一共有"+getSuShuCount2()+"个");
    }
}

  

package com.thread;

public class SuShuDemo1Test {
    public static void main(String[] args) {

        SuShuDemo1 suShuDemo1 = new SuShuDemo1();
        SuShuDemo2 suShuDemo2 = new SuShuDemo2();
        Thread thread = new Thread(suShuDemo2);
        suShuDemo1.start();
        thread.start();
    }
}

  运行结果:

 

Thread-0素数一共有9592个
Thread-1素数一共有8392个

 

  

 

posted @ 2019-05-09 13:23  泰斗贤若如  阅读(829)  评论(0编辑  收藏  举报