java中的多线程同步
缓冲区类具有写入和读取方法。缓冲区由多个线程使用。产生数据的线程使用write方法将数据值写入缓冲区;使用数据的线程调用read方法从缓冲区获取下一个数据值。下面的代码在只有一个线程时有效,但在使用多个线程时读写方法不正确 描述需要进行的4项更改 更正这两种方法的代码,解释每次更改的效果。你可以写下来 如果需要,请输入正确的代码,但这不是必需的java中的多线程同步,java,multithreading,synchronization,Java,Multithreading,Synchronization,缓冲区类具有写入和读取方法。缓冲区由多个线程使用。产生数据的线程使用write方法将数据值写入缓冲区;使用数据的线程调用read方法从缓冲区获取下一个数据值。下面的代码在只有一个线程时有效,但在使用多个线程时读写方法不正确 描述需要进行的4项更改 更正这两种方法的代码,解释每次更改的效果。你可以写下来 如果需要,请输入正确的代码,但这不是必需的 public class Buffer<E> { private int maxSize ; // the maximum len
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);
}
}
我的尝试
一个变化是,我们需要同步以避免多个线程同时读/写,但我不确定还有什么其他变化可以最好地改用并发队列
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();
}
}
你能展示你的尝试吗?您对多线程有多少了解?您可以使用并发集合。或者可能是AtomicReferenceArray。您的代码不会从明显的编译问题中编译出来,条目应该是私有的,您可以在声明和构造函数中初始化它。您的编辑修复了一个编译问题,并引入了另一个。@MadConan现在可以了:。我只是给出了一个简单的想法。