you can see that after player4 started using guns also player3 and he
shouldn't.
The synchronization block will not tell threads to skip that block if a threads is already inside. It just tells the thread to wait until the other thread is finished. Therefore, in your code all threads will execute all the those three blocks protected by the synchronized
, regardless of how long the thread stay inside that block sleep(2000);
albeit the execution of those blocks will be performed sequentially.
If you want to limit the number of threads that can access a certain resource (e.g., execute a block of code) you need to use Semaphore (or alike) for that purpose.
what I am trying to do is that when a player using an object no one
else should be able to access it until the player finished.
If by object you mean separately the guns
, drugs
, money
. Then you achieve that there will not be multiple player (i.e., threads) using those objects simultaneously.
If by "after the player have finish" you mean the entire run then you need to synchronize the entire block of the run()
method using a single lock.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…