java thread lock details and example code

  • 2020-05-26 08:34:03
  • OfStack

java thread lock

Use the synchronized keyword in the Java thread to achieve synchronization

synchronized can lock methods, lock classes, lock objects, lock code blocks

Methods the lock


//  The synchronization lock is added to the method this
  public synchronized void print() {
    System.out.println(" Synchronized methods ");
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

Kind of lock


public synchronized void print(String msg) {
    //  Kind of lock 
    synchronized (MyThread.class) {
      System.out.println(msg);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

Object lock

Take selling train tickets


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) {
      //  Synchronized code block 
      // 1 The lock   The key 
      //  All threads   You have to line up here 
      synchronized (obj) {
        if (tick > 0) {
          System.out.println(getName() + " Sold the first one. " + tick + " 】 a ticket ");//  lost cpu resources 
          tick--;
        }
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

  }
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: