java thread lock
Use synchronized keywords in Java threads to achieve synchronization
synchronized can lock methods, lock classes, lock objects, lock code blocks
Method lock
// The synchronization lock added to the method is this public synchronized void print() { System.out.println("Synchronized method"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }Class lock
public synchronized void print(String msg) { // Class lock synchronized (MyThread.class) { System.out.println(msg); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } } Object lock
Take the train tickets as an example
public class Window extends Thread { public Window(String name) { super(name); } static int tick = 100; static String obj = new String(); @Override public void run() { // Start selling tickets while (tick > 0) { // Synchronize code block// A lock key// All threads must queue here synchronized (obj) { if (tick > 0) { System.out.println(getName() + "Selled the [" + tick + "] ticket");// Lost the cpu resource tick--; } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }}Thank you for reading, I hope it can help you. Thank you for your support for this site!