【发布时间】:2015-12-18 20:40:15
【问题描述】:
我需要实现一个使用带有 peek() 方法的队列的共识协议,以表明可以为任意数量的线程达成共识,即带有 peek() 方法的队列具有无限共识编号
这是我的代码
import java.util.LinkedList;
import java.util.Queue;
public class PeekConsensus extends ConsensusProtocol<Integer>
{
Queue<Integer> queue ;
public PeekConsensus(int threadCount)
{
super(threadCount); //threadCount is a command line argument from the main class specifying the number of threads to handle this process
queue = new LinkedList<Integer>() //FIFO queue
}
public Integer decide(Integer value)
{
this.propose(value); // stores "value" in a vector named proposed, at index ThreadID.get()
int i = ThreadID.get() ;
queue.add(i)
System.out.println("Thread " + i + " : " + i) ; // Required by specifications to print thread id and the value added when an item is enqueued
System.out.println("Thread " + i + " : " + queue.peek()) ; // Required by specifications to print thread id and the value of peek() when when peek() is called
return proposed.elementAt(queue.peek()) ;
}
}
据我了解,这应该可行,因为如果两个线程返回不同的值,peek() 将不得不返回不同的线程 ID,并且确保有效性,因为每个线程在推送其线程 ID 之前将其自己的值写入提议。
是否有人能够找出我哪里出错并指导我纠正我的代码
【问题讨论】:
-
我们必须先知道它有什么问题。
-
不清楚您看到的是什么错误,但一个问题可能是 LinkedList 不是线程安全的。使用 Queue 的线程安全变体可能会有所帮助。
-
将新的 LinkedList 更改为新的 LinkedBlockingQueue() 可能会让你走到一半……
标签: java multithreading fifo consensus