java多线程获取锁无法正常工作

时间:2016-10-13 21:08:27

标签: java multithreading locking wait notify

我试图编写一小段代码来锁定和解锁一段代码。 acquire_lock和release_lock函数如下:

    public static void acquire_lock(long timestamp) {
    synchronized(operations) {
        // put the timestamp into queue
        operations.add(timestamp);
        // check if the head of queue is current timestamp, if not,
        // this means there are some other operations ahead of current one
        // so current operation has to wait
        while (operations.peek() != timestamp) {
            try {
                operations.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public static void release_lock() {
    synchronized(operations) {
        // poll the finished operation out of queue
        // and wake up all waiting operations
        operations.poll();
        operations.notifyAll();
    }
}

但是,当我将此代码放入测试环境时,它并不总是运行良好, 整个测试代码如下:

public class AcquireLockNotWork {

static int balance = 0;
static PriorityQueue<Long> operations = new PriorityQueue<Long>();

// withdraw money from balance
public static void withdraw(final int amt) {
    // get system time
    Long timestamp = System.nanoTime();
    Thread t = new Thread(new Runnable() {
        public void run() {
            // try to use acquire_lock to lock this piece of code
            acquire_lock(timestamp);
            try {       
                Thread.sleep(500);
                int holdings = balance;
                balance = holdings - amt;
                System.out.println("Withdrew " + amt + " from funds. Now at " + balance);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                release_lock();
            }       
        }
    });
    t.start();
}

//put money into banlance
public static void deposit(int amt) {
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            Long timestamp = System.nanoTime();
            acquire_lock(timestamp);
            int holdings = balance;
            balance = holdings + amt;
            System.out.println("deposit " + amt + ", balance: " + balance);
            release_lock();
        }
    });
    t1.start();
}

public static void acquire_lock(long timestamp) {
    synchronized(operations) {
        // put the timestamp into queue
        operations.add(timestamp);
        // check if the head of queue is current timestamp, if not,
        // this means there are some other operations ahead of current one
        // so current operation has to wait
        while (operations.peek() != timestamp) {
            try {
                operations.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public static void release_lock() {
    synchronized(operations) {
        // poll the finished operation out of queue
        // and wake up all waiting operations
        operations.poll();
        operations.notifyAll();
    }
}

public static void test1() {
    balance = 0;
    deposit(2000);
    withdraw(500);
    withdraw(1000);
}

public static void main(String[] args) {
    test1();
}
}

少数次,结果如下:

deposit 2000, balance: 2000
Withdrew 500 from funds. Now at 500
Withdrew 1000 from funds. Now at 500

这意味着acquire_lock和release_lock函数不能很好地工作。似乎最后两个线程(撤回500并撤回1000)同时进入acquire_lock()和release_lock()之间的块,这不是我想要的。 那么acquire_lock和release_lock函数有什么问题呢?

1 个答案:

答案 0 :(得分:0)

这里非常棘手。 异常发生是因为后一个线程首先进入acquire_lock。当较早的线程进入acquire_lock时,它不会被阻塞,因为代码会根据时间戳阻塞线程。因此,两个线程转到相同的 protected 代码区域。