Java thread synchronization-synchronized
Synchronized: synchronization (lock), which can modify code blocks and methods. Once the modified code blocks and methods are accessed by one thread, they are locked directly, and other threads will not be able to access the synchronization lock object of non-static methods is this.
The lock synchronization object of the static method is the bytecode object of the current class
A case of simulated ticket sales at railway station
Synchronize code blocks:
Public class Ticket implements Runnable {
Int tickets = 100 if / Total votes Object obj = new Object (); / / Lock object @ Overridepublic void run () {/ / ticket selling while (true) {synchronized (obj) {if (tickets > 0) {try {Thread.sleep (10);} catch (InterruptedException e) {e.printStackTrace () } System.out.println (Thread.currentThread (). GetName () + "sold" + (tickets--) + "ticket");}
}
Synchronization method
Public class Ticket implements Runnable {
Int tickets = 100 if / Total votes Object obj = new Object (); / / Lock object @ Overridepublic void run () {/ / ticket selling while (true) {method ();}} public synchronized void method () {if (tickets > 0) {try {Thread.sleep (10);} catch (InterruptedException e) {e.printStackTrace () } System.out.println (Thread.currentThread (). GetName () + "sold" + (tickets--) + "ticket");}}
}
Test class
Public class TicketTest {
Public static void main (String args []) {
Ticket t = new Ticket (); Thread T1 = new Thread (t); Thread T2 = new Thread (t); Thread T3 = new Thread (t); t1.setName (window 1); t2.setName (window 2); t3.setName (window 3); t1.start (); t2.start (); t3.start ();}
}