简体   繁体   中英

multiThreading notify and Wait() concept?

Here is the code for fecthing the primenumbers till 100 and storing them in an array. But the problem is the code is not working properly because the second for loop is not waiting till the i is changed. 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 + " ");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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