简体   繁体   English

多线程通知和 Wait() 概念?

[英]multiThreading notify and Wait() concept?

Here is the code for fecthing the primenumbers till 100 and storing them in an array.这是将质数转化为 100 并将它们存储在数组中的代码。 But the problem is the code is not working properly because the second for loop is not waiting till the i is changed.但问题是代码无法正常工作,因为第二个 for 循环没有等到 i 更改。 Can anybody help me to figure out what the problem is?有人可以帮我弄清楚问题是什么吗?

       synchronized (this) {
        boolean stop = false;
        boolean change = false;
        int primenumber[]= new int[20];
        System.out.println("The prime numbers are : ");
        for (int i = 1; i <= 100; i++) {
            int count = 0;
            change = true;
            notify();
            for (int num = i; num >= 1; num--) {
                if (i % num == 0) {
                    count = count + 1;
                }
            }
            if (count == 2) {
                if (!stop) {
                    for (int ab = 0; ab <= 20; ab++) {
                        primenumber[ab] = i;
                        while (!change) {
                            try {
                                wait();
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
            }
        }
    }
int num = 0;
    System.out.println("Please Enter n.");
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    scanner.close();

    System.out.println("\nPrime Numbers up to " + n + ".");

    for (int i = 1; i <= n; i++) {
        int counter = 0;
        for (num = i; num >= 1; num--) {
            if (i % num == 0) {
                counter++;
            }
        }

        // Counter = 2 means number is only divisible by 1 and the number itself. So it's a prime number.
        if (counter == 2) 
        {
            System.out.print(i + " ");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM