An interesting phenomenon about JAVA multithreading

Simulate a ticketing system, or withdraw money from a bank.

 

class Bank {

  synchronized getmoney(){

    //Sleep is required here, in order to slow down the speed.

  }

}

 

class Customer extends Thread{

  withdraw(){

    loop 100 times {

       getmoney() 

        //Interestingly, sleep is also required here.       

    }

  }

}

 

class  test{

  main(){

    Customer 1.start()

    customer 2.start()

  }

}

For such a topic, I used to only need to sleep when I was withdrawing money, but I didn't realize it until I wrote it. Where the loop is also put to sleep.

Otherwise, there will be a situation where customer 2 starts after customer 1 is finished.

 

It feels that the loop will send out the task of withdrawing money 100 times at a time. Although the withdrawal of money is slower each time (you need to sleep), the task distribution is very fast.

It is not after withdrawing money, returning to the loop, and then randomly deciding on customer N to execute.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325247568&siteId=291194637