jeudi 31 janvier 2019

2 threads always have get the same results by using random methods

Thread t1 = new Thread(new Runnable() {
        public void run(){
            int i = 0;
            while(secondsPassed <= 5) {
                while(list.length()<4 && secondsPassed <= 5);
                Random r = new Random();
                if(r.nextInt(100) < 10) {
                    list.removeFirst();
                    i++;                
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                       
                }
            }
            System.out.println("Thread t1 is finished with  "+ i);
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run(){
            int i = 0;
            while(secondsPassed <= 5) {
                Random a = new Random();
                System.out.println("Thread t2 is turn  "+ i + "with" + a.nextInt(100));
                char c = (char)(a.nextInt(23) + 'D');
                if(a.nextInt(100) < 10) {
                    list.insert(c);
                    i++;
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("Thread t2 is finished with  " + i);
        }
    });

For my thread 1 and thread 2 they are expecting to remove and adding a node into the linked list, and they are constrainted by Random() method of a possibility of 10%, and after each turn, they will sleep for 20ms. However, everytime I run my program, thread 1 and 2 will always generate the same possiblities.




Aucun commentaire:

Enregistrer un commentaire