线程安全LinkedList交替使用

AKI*_*WEB 0 java multithreading thread-safety

目前我正在使用LinkedList添加所有Command信息.如何使下面的List<Command>线程安全?我应该在这里使用其他选项而不是LinkedList吗?

private static List<Command> commands;

Command command = new Command();
command.setName(commandName);
command.setExecutionPercentage(Double.parseDouble(percentage));
command.setAttributeIDGet(attributeIDGet);
command.setAttributeIDSet(attributeIDSet);
command.setDataUsageCriteria(dataCriteria);
command.setUserLoggingCriteria(userLoggingCriteria);
command.setSleepTime(sleepTimeOfCommand);
Run Code Online (Sandbox Code Playgroud)

command正在通过从文本文件中读取并将其放入LinkedList of command如下所示的内容中添加以上所有内容.所以如果我有,three command那么我需要将所有这些添加three command到一些LinkedList我正在做的事情中.

commands.add(command);
Run Code Online (Sandbox Code Playgroud)

如果我做下面的事情怎么办? -

Collections.synchronizedList(commands.add(command));
Run Code Online (Sandbox Code Playgroud)

或者我需要做这样的事情 -

commands = Collections.synchronizedList(new LinkedList<Command>());
Run Code Online (Sandbox Code Playgroud)

更新: -

根据你的建议,如果我正在使用 -

private static Queue<Command> commands;


commands = new ConcurrentLinkedQueue<Command>(); // Using linked list to ensure iteration order



Command command = new Command();
command.setName(commandName);
command.setExecutionPercentage(Double.parseDouble(percentage));
command.setAttributeIDGet(attributeIDGet);
command.setAttributeIDSet(attributeIDSet);
command.setDataUsageCriteria(dataCriteria);
command.setUserLoggingCriteria(userLoggingCriteria);
command.setSleepTime(sleepTimeOfCommand);


commands.add(command);
Run Code Online (Sandbox Code Playgroud)

基本上在所有初始化完成后的某个时间之后,我需要command information从队列中获取,所以我之前使用的是做了类似的事情LinkedList.但是在chaning之后ConcurrentLinkedQueue,这get call is giving me an error就像有一个error line on get call

commands.get(commandWithMaxNegativeOffset);
Run Code Online (Sandbox Code Playgroud)

错误我得到 -

 The method get(int) is undefined for the type Queue<Command>
Run Code Online (Sandbox Code Playgroud)

Gra*_*ray 8

ConcurrentLinkedQueue是并发链接队列.引用javadocs:

基于链接节点的无界线程安全队列.此队列对元素FIFO(先进先出)进行排序.队列的头部是队列中最长时间的元素.队列的尾部是队列中最短时间的元素.新元素插入队列的尾部,队列检索操作获取队列头部的元素.当许多线程共享对公共集合的访问时,ConcurrentLinkedQueue是一个合适的选择.此队列不允许null元素.

所以你要做的事情如下:

 Queue<Command> concurrentQueue = new ConcurrentLinkedQueue<Command>();
 Command command = new Command();
 ...
 concurrentQueue.add(command);
Run Code Online (Sandbox Code Playgroud)

你也可以List使用包裹你的当前Collections.synchronizedList(...).是否执行此操作或使用ConcurrentLinkedQueue取决于您需要集合的高性能.

// turn the commands list into a synchronized list by wrapping it
commands = Collections.synchronizedList(commands);
Run Code Online (Sandbox Code Playgroud)

如果您提供有关如何使用此队列的更多信息,我们可以根据正确的JDK并发集合提供更多替代方案.

Collections.synchronizedList(commands.add(命令));

您编辑了您的问题并询问了上述代码.它将不会编译,因为List.add(...)返回一个布尔值.