/* Pre-sync title: 1. Must have two or 2. Must be multiple threads to use one lock advantage: To solve the problem of multithreading security: Multiple threads to determine the lock, consume resources */Package pack; Public class Main { Public Static voidMain (string[] args) {//TODO auto-generated method stubTicket T =NewTicket (); Thread T1 =NewThread (t); Thread t2 =NewThread (t); Thread t3 =NewThread (t); Thread T4 =NewThread (t); T1.start (); T2.start (); T3.start (); T4.start (); } Public Static voidSYS (Object obj) {System.out.println (obj); }}/*class Ticket implements Runnable {//sync code block Object obj = new Object (); private int tick = 100; public void Run () {while (true) {synchronized (obj) {if (tick>0) main.s Ys (Thread.CurrentThread (). GetName () + "---" +tick--); } } }}*/ class Ticket implements Runnable { //Sync functionObject obj =NewObject ();Private intTick = -; Public voidRun () { while(true) {Show (); } } PublicSynchronizedvoidShow () {if(tick>0) Main.sys (Thread.CurrentThread (). GetName () +"---"+tick--); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java thread Synchronization