Synchronized: Synchronization (lock), can be decorated code blocks and methods, the modified code blocks and methods once accessed by a thread, it is directly locked, other threads will not be able to access
The synchronous lock object of a non-static method is this
The static method's lock synchronization object is the bytecode object of the current class
Mock train station ticketing case
Synchronizing code blocks:
public class Ticket implements Runnable {
int tickets = 100;//总票数Object obj = new Object(); //锁对象@Overridepublic void run() { //卖票 while (true) { synchronized (obj) { if (tickets > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖出了第" + (tickets--) + "张票"); } } }}
}
Synchronization method
public class Ticket implements Runnable {
int tickets = 100;//总票数Object obj = new Object(); //锁对象@Overridepublic void run() { //卖票 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() + "卖出了第" + (tickets--) + "张票"); }}
}
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("窗口1"); t2.setName("窗口2"); t3.setName("窗口3"); t1.start(); t2.start(); t3.start();}
}
Java thread Synchronization-synchronized