java lock 出现诡异。
大家讲道理
大家讲道理 2017-04-18 09:55:28
0
1
372

在温习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("获得锁失败");
            }

        }
    }
}

有时输出结果:

有时输出结果:

个人认为第二种结果是期望的正确结果,第一种结果不符合锁的机制。
望各位能多发表自己的看法,若能解开疑惑,不胜感激。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

membalas semua(1)
阿神

Alihkan sahaja ayat ini: System.out.println(Thread.currentThread().getName() + "已释放锁");
di hadapan lock.unlock();

try {
    System.out.println(Thread.currentThread().getName() + "已释放锁");
} finally {
    if (flag || !flag) {
        lock.unlock();
    }
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan