We created 4 threads, which, unlike before, used synchronous functions and synchronized code quickly. See how it turns out.
classMlpcImplementsrunnable{Private intTicket = 550; Public BooleanFlag =true; Object obj=NewObject (); Public voidrun () {if(Flag = =true) { while(true) { synchronized (obj) {if(ticket>0) { if(ticket>0) { Try{Thread.Sleep (20); } Catch(Exception e) {} System.out.println (Thread.CurrentThread ()+ "Show" +ticket--); } } } } } Else { while(true) {show (); } } } Public synchronized void Show () {if(ticket>0) { Try{Thread.Sleep (20); } Catch(Exception e) {} System.out.println (Thread.CurrentThread ()+ "Show" +ticket--); } }} classMlpcdemo { Public Static voidMain (string[] args) {MLPC m=NewMLPC (); Thread Th0=NewThread (m); Thread Th1=NewThread (m); Thread Th2=NewThread (m); Thread Th3=NewThread (m); Th0.start (); Try{Thread.Sleep (20); } Catch(Exception e) {} M.flag=false; Th1.start (); Th2.start (); Th3.start (); }}
The result was a vote of 0.
Public voidrun () {if(Flag = =true) { while(true) { synchronized ( This)//change from the original arbitrary object to a functionthe object to which you belongThis
{ if(ticket>0) { Try{Thread.Sleep (20); } Catch(Exception e) {} System.out.println (Thread.curr Entthread ()+ "Show" +ticket--); } } } } Else { while(true) {show (); } } }
Multithreading (understanding of 1_ lock _2_ deadlock analysis)