2022-02-06 多线程练习题

1个线程输出前100万个素数,1个线程输出前100万个不能被3整除的数。
在两个线程完成工作后停止时间计数器。

https://gist.github.com/augustrobo/7fd8a10f9116e29d726be26d649fbc3c
NumsFinder.java
启动两个线程,以及时间计数。

public class NumsFinder {
    public static void main(String[] args) {
        int time = 0;
        PrintNums t1 = new PrintNums("3");
        t1.start();
        PrintNums t2 = new PrintNums("prime");
        t2.start();
        while(true) {
            System.out.println(time);
            try{
                Thread.sleep(1000);
            } catch(InterruptedException exc) {
                // do nothing
            }
            if (t1.isThreadOver() && t2.isThreadOver()) {
                break;
            }
            time++;
            }
        System.out.println("\nTime elapsed: " + time + " seconds");
    }
}

PrintNums.java
Thread的子类,根据不同的输入num_type决定输出是素数还是与num_type互素的数。

public class PrintNums extends Thread {
    private String num_type;
    private StringBuffer nums = new StringBuffer();
    public PrintNums(String num_type) {
        this.num_type = num_type;
    }
    
    public void run() {
        int quantity = 1_000_000;
        int num_cnt = 0;
        if (num_type.equals("prime")) {
            int candidate = 2;
            nums.append("\nFirst ").append(quantity).append(" primes:\n\n");
            while(num_cnt < quantity) {
                if (isPrime(candidate)) {
                    nums.append(candidate).append(" ");
                    num_cnt++;
                }
                candidate++;
            }
        } else {
            int candidate = 1;
            int k = Integer.parseInt(num_type);
            nums.append("\nFirst ").append(quantity).append(" relative prime to " + num_type + ":\n\n");
            while(num_cnt < quantity) {
                if (isRelativePrime(candidate, k)) {
                    nums.append(candidate).append(" ");
                    num_cnt++;
                }
                candidate++;
            }
        }
        System.out.println(nums); 
        nums = null;
    }
    
    public static boolean isPrime(int checkNumber) {
        double root = Math.sqrt(checkNumber);
        for (int i = 2; i <= root; i++){
            if (checkNumber % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean isRelativePrime(int checkNumber, int k) {
        return checkNumber % k != 0;
    }
    
    public boolean isThreadOver() {
        return nums == null;
    }
}

运行结果如图:


image.png

你可能感兴趣的:(2022-02-06 多线程练习题)