【问题标题】:Multiple threads synchronization in java [duplicate]java中的多线程同步[重复]
【发布时间】:2015-07-25 03:21:01
【问题描述】:

Buffer 类具有方法 writeread。缓冲区由多个线程使用。产生数据的线程使用write 方法将数据值写入缓冲区;消费数据的线程调用read 方法从缓冲区获取下一个数据值。下面的代码,在只有单线程的情况下有效,但是在多线程的情况下readwrite方法不正确。

描述需要进行的 4 项更改 更正两种方法的代码,说明每次改动的效果。 (你可以写出 如果您愿意,可以使用更正后的代码,但这不是必需的。)

public class Buffer<E> {

    private int maxSize ; // the maximum length of the buffer
    private List<E> entries ; // the entries in the buffer

    // constructor
    public Buffer(int maxSize) {
        entries = new ArrayList();
        this.maxSize = maxSize;
    }

    public void write(E entry) {
        entries.add(entry);
    }

    public E read() {
        return entries.remove(0);
    }

}

我的尝试

一个改变是我们需要同步来避免多个线程同时读/写,但我不确定我还能做哪些其他改变

【问题讨论】:

  • 你能展示你的尝试吗?你对多线程了解多少?
  • 您可以使用并发集合。或者可能是AtomicReferenceArray

标签: java multithreading synchronization


【解决方案1】:

最好改用并发队列

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Buffer {
    private int maxSize; // the maximum length of the buffer
    public Queue<String> entries = new ConcurrentLinkedQueue<String>();
    private static Buffer instance;

    // constructor
    public static Buffer getInstance() {
        return instance = new Buffer();
    }

    public void write(String entry) {
        entries.add(entry);
    }

    public synchronized String read() {
        return entries.poll();
    }
}

【讨论】:

  • 你的代码不会编译
  • 除了明显的编译问题之外,entries 应该是私有的,并且您在声明和构造函数中对其进行初始化。
  • 您的编辑修复了一个编译问题并引入了另一个。
  • @MadConan 现在可以了 :) 。我只是给出一个简短的想法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
相关资源
最近更新 更多