One, multiple threads, single lock
PackageCom.sun.multithread.sync; Public classMyThreadextendsThread {Private intCount = 5; //Synchronized Locking Public synchronized voidRun () {count--; System.out.println ( This. CurrentThread (). GetName () + "Count =" +count); } Public Static voidMain (string[] args) {MyThread MyThread=NewMyThread (); Thread T1=NewThread (MyThread, "T1"); Thread T2=NewThread (MyThread, "T2"); Thread T3=NewThread (MyThread, "T3"); Thread T4=NewThread (MyThread, "T4"); Thread T5=NewThread (MyThread, "T5"); T1.start (); T2.start (); T3.start (); T4.start (); T5.start (); }}
Two, multiple lines multithreading lock
PackageCom.sun.multithread.sync; Public classmultithread {Private Static intnum = 0; /*** Add synchronized keyword to static method, means lock class class, Class-level lock * keyword synchronized acquired lock is object lock, rather than a piece of code (method) as a lock, * so which thread in the code executes the first synch Ronized method of the keyword, which thread holds the lock of the object to which the method belongs *@paramTag Parameter*/ Public Static synchronized voidprintnum (String tag) {Try { if(Tag.equals ("a") ) {num= 100; System.out.println ("Tag A, set num over!"); Thread.Sleep (1000); } Else{num= 200; System.out.println ("Tag b, set num over!"); } System.out.println ("Tag" + tag + ", num =" +num); } Catch(interruptedexception e) {e.printstacktrace (); } } Public Static voidMain (string[] args) {//two different objects FinalMultithread M1 =Newmultithread (); Finalmultithread m2 =Newmultithread (); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {M1.printnum (A); } }); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {M1.printnum ("B"); } }); T1.start (); T2.start (); }}
Some small demo of multithreading