When Java multithreading processes the same resource, threads rarely run alternately.

  java, question

In Java learning, I am currently watching multithreading.
The example debugged is a classic multi-point ticketing program.
In order to prevent ticket outlets from selling tickets that exceed the actual number of votes due to out-of-sync resources
The synchronized keyword is used
As a result, it will not sell another -1 ticket
However, the debugging result seems not ideal. If the number of votes is small, it is basically the first ticket selling point that has sold out.
Even if there are a large number of votes (100), the threads are not running alternately, but all A and all B at one time.

Please help check whether the code is wrong and the logic is reasonable.
Thank you!

Code:

class Test24_04 implements Runnable{
 private int piao = 10;
 public void run(){
 while(this.piao > 0){
 this.fun();
 bracket
 bracket
 public synchronized void fun(){
 if(this.piao > 0){
 try{
 Thread.sleep(100);
 }catch(Exception e){
 ;
 bracket
 System.out.println (thread.currentthread (). getname () added "sold" and the remaining votes: "this.piao--);
 bracket
 bracket
 bracket
 
 public class JavaTest24_04{
 public static void main(String args[]){
 Test24_04 t = new Test24_04();
 Threatt1 = newthread (t, "ticket point a");
 Threatt2 = newthread (t, "ticket point b");
 ThreatT3 = newthread (t, "ticket point c");
 t1.start();
 t2.start();
 t3.start();
 bracket
 bracket
 
 
 //Use the synchroized keyword to realize the synchronization operation of threads on resources

It seems that it involves java’s internal bottom-level implementation. It seems that thread will apply again immediately after releasing the monitor lock, thus having a better chance of obtaining the monitor.

Put sleep () in run () inside to avoid such problems and get the desired results.

public void run(){
 while(this.piao > 0){
 this.fun();
 try{
 Thread.sleep(100);
 }catch(Exception e){}
 bracket
 bracket
 
 public synchronized void fun(){
 if(this.piao > 0)
 System.out.println (thread.currentthread (). getname () added "sold" and the remaining votes: "this.piao--);
 bracket