Home > front end >  Multithreading with a While Loop
Multithreading with a While Loop

Time:02-15

So below is my code where Buyers and Sellers interact with Cars and a Car Showroom. It runs as it should, as far as I know. However, Threads only run after day 20 in the While Loop in Main. Could anyone help point out why this is?

public static void main(String[] args) {

    CarShowroom carShowroom = new CarShowroom();
    Random rand = new Random();

    int day = 1;

    while (day <= 30){
       System.out.println("Day "   day   " beginning. There are "   carShowroom.getCars().size()    " cars in the showroom today.");

        int randomSeller = rand.nextInt(3);
        int randomBuyer = rand.nextInt(3);

        for (int j = 0; j <= randomSeller; j  ){
            Seller seller = new Seller(carShowroom);
            Thread mySellerThread = new Thread(seller);
            mySellerThread.start();
        }

        for (int i = 0; i <= randomBuyer; i  ){
            Buyer buyer = new Buyer(carShowroom);
            Thread myBuyerThread = new Thread(buyer);
            myBuyerThread.start();
        }

        day  ;
    }
}

}

CodePudding user response:

I think perhaps your loop is executing quicker than Thread.start() will start.

CodePudding user response:

It is either caused by the fact that spawned threads are not immediately ready to execute code or simply you might have single core machine and main thread occupies cpu then the other threads have to wait until cpu time slice assigned to the main thread ends. In order to achieve tiny bit of determinism within yours program execution, you could put Thread.sleep(100) in the main loop to create an opportunity for the other threads to run. That should alter the order of execution.

  • Related