在温习java lock锁时遇见不能接受的输出结果。
package com.roysatm.concurrency; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by roysatm on 2016/9/3. */ public class ReviewLock { private static int a = 0; static Lock lock = new ReentrantLock(); public static void main(String[] args) { LockTest lt = new LockTest(); Thread t1 = new Thread(lt); Thread t2 = new Thread(lt); t1.start(); t2.start(); while (t1.isAlive() || t2.isAlive()); System.out.println("a = " + a); } static class LockTest implements Runnable { @Override public void run() { boolean flag = false; // try { // flag = lock.tryLock(200, TimeUnit.MILLISECONDS); // } catch (InterruptedException e) { // e.printStackTrace(); // } lock.lock(); if (flag || !flag) { System.out.println(Thread.currentThread().getName() + "已获得锁"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 10; i++) { a++; } try { } finally { if (flag || !flag) { lock.unlock(); } System.out.println(Thread.currentThread().getName() + "已释放锁"); } } else { System.out.println("获得锁失败"); } } } }
有时输出结果:
有时输出结果:
个人认为第二种结果是期望的正确结果,第一种结果不符合锁的机制。
望各位能多发表自己的看法,若能解开疑惑,不胜感激。
把这句:
System.out.println(Thread.currentThread().getName() + "已释放锁");
移到
lock.unlock();
前面去就对了