简体   繁体   中英

Generating infinite sequence of numbers using 7 threads

I am trying to generate infinite sequence of numbers using different threads in Java . Here is my code :

import java.util.*;

public class infinite_Streams {
    volatile boolean keepGenerating = true;
    volatile ArrayList<Integer> s1 = new ArrayList<>();
    Object lock1 = new Object();
    Random random = new Random();
    ArrayList<Object> obj1 = new ArrayList<>();


    void  generateInfiniteStream() {

        synchronized (lock1) {

        //BLOCK 1
            while(keepGenerating) {
                Object temp = Thread.currentThread().getId();
                System.out.println("Thread is : " + temp);
                s1.add(random.nextInt(11));
            }
            }
            //BLOCK 1 ENDS

        //BLOCK 2

//            for (int i = 0; i < 100000; i++) {
//                Object temp = Thread.currentThread().getId();
//                System.out.println("Thread is : " + temp);
//                s1.add(random.nextInt(11));
//            }
        //BLOCK 2 ENDS
    }

    void generateThreads(int num_threads){
        Thread[] threads = new Thread[num_threads];

        for(int i = 0 ; i < num_threads ; i++){
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    generateInfiniteStream();
                }
            });
        }

        for (Thread thread : threads) {

            thread.start();
        }


        try{
            for (Thread thread : threads) {
                thread.join();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    public void shutdown(){
        keepGenerating = false;
    }


    public static void main(String [] args){
        List<Integer> l1 = new ArrayList<>();
        int num_threads = 7;
        Scanner scan1 = new Scanner(System.in);
        infinite_Streams is1 = new infinite_Streams();

        is1.generateThreads(num_threads);
        System.out.println("Press any key to interrupt");
        Scanner scan2 = new Scanner(System.in);
        scan2.nextLine();
        is1.shutdown();
    }
}

The code does seem to generate what i need . But i am also interested to see how different threads are involved.To see this i printed (can be seen in \\\\BLOCK1 )

Object temp = Thread.currentThread().getId();
 System.out.println("Thread is : " + temp);

The problem is that i only see a particular thread , say 12 , so the output looks like Thread is : 12 always . On the other hand , if i comment the \\\\BLOCK1 code and instead run the \\\\BLOCK2 code, which generate a finite number of numbers, i see different thread number , in the output as expected . Like Thread is : 12 Thread is : 12 Thread is : 14 etc. Can someone explain , why i am not seeing different thread numbers while generating infinite numbers ?

One of threads obtains the lock. Then it is executing while(keepGenerating) until you change this variable. All other threads are waiting until the lock is free. When you set keepGenerating to false , then the running threads completes the loop. One of other threads obtains the lock. But at this moment keepGenerating is already false, so that it does not execute this loop and just exits. Then the next threads obtains the lock and again sees that there is nothing to do. Etc.

So actually only one of threads is generating random numbers.

If you want that every thread generates random numbers, you should use while(keepGenerating) not within synchronized block, but outside of it, like following:

while(keepGenerating) {
    synchronized (lock1) {
        Object temp = Thread.currentThread().getId();
        System.out.println("Thread is : " + temp);
        s1.add(random.nextInt(11));
    }
}

Then every thread will get the lock not for ever , but just for a single execution of the generation of number and for output. Then lock will be freed and other thread can get it, etc.

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