Home > Java > javaTutorial > Detailed introduction and example code of java thread lock

Detailed introduction and example code of java thread lock

高洛峰
Release: 2017-01-11 15:41:17
Original
1378 people have browsed it

java thread lock

Use the synchronized keyword in Java threads to achieve synchronization

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

Method lock

// 加在方法上面的同步锁是this
  public synchronized void print() {
    System.out.println("同步方法");
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Copy after login

Class lock

public synchronized void print(String msg) {
    // 类锁
    synchronized (MyThread.class) {
      System.out.println(msg);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Copy after login

Object lock

Take selling 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() {
    // 开始卖票
    while (tick > 0) {
      // 同步代码块
      // 一把锁 钥匙
      // 所有的线程 必须在这里排队
      synchronized (obj) {
        if (tick > 0) {
          System.out.println(getName() + "卖出了第【" + tick + "】张票");// 失去了cpu资源
          tick--;
        }
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
 
  }
}
Copy after login

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more detailed introductions to java thread locks and articles related to example codes, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template