欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java 線程鎖詳細(xì)介紹及實(shí)例代碼

 更新時(shí)間:2016年12月25日 14:16:32   投稿:lqh  
這篇文章主要介紹了java 線程鎖詳細(xì)介紹及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下

java 線程鎖

在Java線程中運(yùn)用synchronized關(guān)鍵字來(lái)達(dá)到同步的

synchronized可以鎖方法,鎖類,鎖對(duì)象,鎖代碼塊

方法鎖

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

類鎖

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

對(duì)象鎖

以賣火車票為例

public class Window extends Thread {

  public Window(String name) {
    super(name);
  }

  static int tick = 100;
  static String obj = new String();

  @Override
  public void run() {
    // 開(kāi)始賣票
    while (tick > 0) {
      // 同步代碼塊
      // 一把鎖 鑰匙
      // 所有的線程 必須在這里排隊(duì)
      synchronized (obj) {
        if (tick > 0) {
          System.out.println(getName() + "賣出了第【" + tick + "】張票");// 失去了cpu資源
          tick--;
        }
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

  }
}

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論