java 線程鎖
在Java線程中運用synchronized關鍵字來達到同步的
synchronized可以鎖方法,鎖類,鎖對象,鎖代碼塊
方法鎖
// 加在方法上面的同步鎖是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(); } } }對象鎖
以賣火車票為例
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(); } } }}感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答