概述
tryLock(long time, TimeUnit unit)方法和tryLock()方法是類似的,只不過區別在于這個方法在拿不到鎖時會等待一定的時間,在時間期限之內如果還拿不到鎖,就返回false。如果一開始拿到鎖或者在等待期間內拿到了鎖,則返回true。
代碼
@Testpublic void testTryLock2() throws Exception {Lock lock = new ReentrantLock();new Thread() {@Overridepublic void run() {String tName = Thread.currentThread().getName();try {//獲取不到鎖,就等7秒,如果7秒后還是獲取不到就返回falseif (lock.tryLock(7000, TimeUnit.MILLISECONDS)) {System.out.println(tName + "獲取到鎖!");} else {System.out.println(tName + "獲取不到鎖!");return;}} catch (Exception e) {e.printStackTrace();}try {for (int i = 0; i < 5; i++) {System.out.println(tName + ":" + i);}Thread.sleep(3000);} catch (Exception e) {System.out.println(tName + "出錯了!!!");} finally {System.out.println(tName + "釋放鎖!!");lock.unlock();}}}.start();new Thread() {@Overridepublic void run() {String tName = Thread.currentThread().getName();try {//獲取不到鎖,就等7秒,如果7秒后還是獲取不到就返回falseif (lock.tryLock(7000, TimeUnit.MILLISECONDS)) {System.out.println(tName + "獲取到鎖!");} else {System.out.println(tName + "獲取不到鎖!");return;}} catch (Exception e) {e.printStackTrace();}try {for (int i = 0; i < 5; i++) {System.out.println(tName + ":" + i);}} catch (Exception e) {System.out.println(tName + "出錯了!!!");} finally {System.out.println(tName + "釋放鎖!!");lock.unlock();}}}.start();Thread.sleep(15000);//主線程}
運行結果
Thread-0獲取到鎖!
Thread-0:0
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0睡覺......
Thread-0醒了......
Thread-0釋放鎖!!
Thread-1獲取到鎖!
Thread-1:0
Thread-1:1
Thread-1:2
Thread-1:3
Thread-1:4
Thread-1釋放鎖!!