Simulate a ticketing system, or a bank to withdraw money.
Class Bank {
Synchronized Getmoney () {
Here to sleep, in order to slow down the speed.
}
}
Class Customer extends thread{
Withdraw Money () {
Loop 100 times {
Getmoney ()
Interestingly, hibernation is also required here.
}
}
}
Class test{
Main () {
Customer 1.start ()
Customer 2.start ()
}
}
Such a topic, in the past only when the money, there is the need for sleep, did not expect to write when the discovery. The place of the cycle also sleeps.
Otherwise it will appear, customer 1 after the completion of the customer 2 only start the situation.
Feel that the cycle will be a one-time 100 of the task of the money to send out, although each time the money is relatively slow (to sleep), but the task is distributed quickly.
Not after the money, go back to the loop, and then randomly decide the customer n execution.
An interesting phenomenon about Java multi-threading