Lock锁详细讲解
package com.wuming.thread;import java.util.concurrent.locks.ReentrantLock;//測試Lock鎖
public class TestLock {public static void main(String[] args) {TestLock2 testLock2 = new TestLock2();//多個對象操作同一個資源票,不用lock時線程不安全/* 108976543210-1*/new Thread(testLock2).start();new Thread(testLock2).start();new Thread(testLock2).start();}
}
class TestLock2 implements Runnable{int ticketNums=10;//定義lock鎖private final ReentrantLock lock=new ReentrantLock();/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see Thread#run()*/@Overridepublic void run() {while(true){try{lock.lock();//加鎖后,使得線程安全/* 10987654321*/if (ticketNums>0){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(ticketNums--);}else{break;}}finally{//解鎖lock.unlock();}}}
}
總結
- 上一篇: C语言 __TIME__ - C语言零基
- 下一篇: BugkuCTF-MISC题普通的二维码