java Lock接口
java.util.concurrent.locks
接口Lock
public interface Loce
Loce實現提供了比使用synchronized方法和語句可獲得的更廣泛的鎖定操作
import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock; public class IntegerDemo { public static void main(String[] args) { // 創建3個線程對象 SellTicket st = new SellTicket(); Thread t1 = new Thread(st, "窗口1"); Thread t2 = new Thread(st, "窗口2"); Thread t3 = new Thread(st, "窗口3"); // 啟動線程 t1.start(); t2.start(); t3.start(); }} class SellTicket implements Runnable { private int ticket = 100; private Lock lock = new ReentrantLock(); public void run() { while (true) { lock.lock(); if (ticket > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (ticket--) + "張票。"); } lock.unlock(); } }}感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答