On behalf of this method lock, the equivalent of any thread a every time it runs to this method, it is necessary to check if there is any other thread B (or C d, etc.) that is using this method, or wait for thread B (or C D) that is using this method to run this method before running this thread A, no, Running it directly consists of two usages: the Synchronized method and the synchronized block.
Java Multi-threaded ticket case synchronized synchronization with synchronized block for synchronization
PublicStaticvoidMain(string[] args) {The properties of the Runable object represent the total number of ticketsThe Run method of the Runable object implements the ticket action Runnable Runnable =New Runnable () {Privateint count =100;@OverridePublicvoidRun () {while (true) {synchronized (this) {//synchronized objects if Thread CurrentThread = Thread.CurrentThread (); if (Count > 0) {out.println (Currentthread.getname () + "=" + (101-count) + "ticket"); --count; } else {break;}}} }; //open 100 Threads simulation 100 ticket outlets for (int i = Span class= "Hljs-number" >0; I < 100; i++) {new Thread (runnable). Start ();}}
Synchronizing with synchronized method blocks
PublicStaticvoidMain(string[] args) {The properties of the Runable object represent the total number of ticketsThe Run method of the Runable object implements the ticket action Runnable Runnable =New Runnable () {Privateint count =100;@OverridePublicvoidRun() {while (True) {if (Synchronizedmethod ())Break } }public synchronized boolean Span class= "Hljs-title" >synchronizedmethod () {Thread CurrentThread = Thread.CurrentThread (); if (Count > 0) {out.println (Currentthread.getname () + "=" + (101-count) + "ticket"); --count; return FALSE;} return true;}; //open 100 Threads simulation 100 ticket outlets for (int i = Span class= "Hljs-number" >0; I < 100; i++) {new Thread (runnable). Start ();}}
The code output after synchronization is as follows
Thread-0 = 1 Tickets
Thread-0 = 2 Tickets
Thread-0 = 3 Tickets
Thread-4 = 4 Tickets
Thread-4 = 5 Tickets
Thread-2 = 6 Tickets
....
....
Thread-34 = 98 Tickets
Thread-34 = 99 Tickets
Thread-34 = 100 Tickets
Non-synchronous
synchronized Block
Remove the sync block
Synchronized method
Delete the ynchronized keyword
The output is as follows
Thread-0 = 1 Tickets
Thread-0 = 2 Tickets
Thread-2 = 1 Tickets
Thread-2 = 4 Tickets
Thread-2 = 5 Tickets
Thread-2 = 6 Tickets
Thread-2 = 7 Tickets
Thread-4 = 7 Tickets
Thread-1 = 1 Tickets
Thread-1 = 10 Tickets
Thread-1 = 11 Tickets
Thread-1 = 12 Tickets
Thread-1 = 13 Tickets
It can be seen that more than one thread accesses the same ticket
It's obviously unreasonable.
The use of Java multithreaded synchronization synchronized keywords