为什么使用同步关键字而不是不使用同步关键字时,一块Java代码更快?

问题描述 投票:0回答:2

我正在实现线程安全的有界阻塞队列。我可以通过两种方式来设计它。

方法1

class BoundedBlockingQueue {
    int capacity;
    Queue<Integer> queue;

    public BoundedBlockingQueue(int capacity) {
        this.capacity = capacity;
        this.queue = new LinkedList();
    }

    public void enqueue(int element) throws InterruptedException {
        while(queue.size() == capacity);
        queue.add(element);
    }

    public int dequeue() throws InterruptedException {
        while(queue.size() == 0);
        return queue.remove();
    }

    public int size() {
        return queue.size();
    }
}

这里,在入队时,进程将继续循环while循环(请注意while条件之后的立即数;),并且仅当queue.size()小于容量时才继续进行。当queue.size()等于0时,也存在类似的逻辑用于出队。

设计同一事物的第二种方法是使用synchronized关键字,如下所示:

方法2

class BoundedBlockingQueue {
    int capacity;
    Queue<Integer> queue;

    public BoundedBlockingQueue(int capacity) {
        this.capacity = capacity;
        this.queue = new LinkedList();
    }

    public void enqueue(int element) throws InterruptedException {
        synchronized(queue){
            while(queue.size() == capacity) queue.wait();
            queue.add(element);
            queue.notifyAll();
        }
    }

    public int dequeue() throws InterruptedException {
        synchronized(queue){
            while(queue.size() == 0) queue.wait();
            int val = queue.remove();
            queue.notifyAll();
            return val;
        }
    }

    public int size() {
        return queue.size();
    }
}

这里,我们使流程等待相同的情况,只有在另一个流程通知这样做时,流程才继续进行。唯一的不同是,我们在方法2中使用的是synchronized关键字,但在方法1中却没有使用。

观察到,方法1比方法2占用了更多的运行时间。为什么会这样呢?两种方法的基本逻辑是否完全相同?与方法2相比,为什么方法1需要更多的运行时间?]

任何帮助将不胜感激。

java multithreading thread-safety mutex synchronized
2个回答
0
投票

上面的代码具有竞争条件,因此第一个示例未提供与第二个示例相同的同步保证。


0
投票

您的第一个方法是不是

© www.soinside.com 2019 - 2024. All rights reserved.