1

現在、すべての情報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);

commandテキストファイルから読み取って、LinkedList of command以下のように配置することで取得した上記のすべてを追加しています。もし私が持っているなら、私がやっていたいくつかにthree commandそれらすべてを追加する必要があるとします。three commandLinkedList

commands.add(command);

以下のようなことをするとどうなりますか?-

Collections.synchronizedList(commands.add(command));

または私はこのようなことをする必要があります-

commands = Collections.synchronizedList(new LinkedList<Command>());

アップデート:-

あなたの提案によると、私が使用している場合-

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);

そして、基本的にすべての初期化が完了した後command information、キューから を取得する必要があるため、以前は を使用してこのようなことをしていましたLinkedList。しかし、 に変更した後ConcurrentLinkedQueue、これget call is giving me an errorがあるのでerror line on get call

commands.get(commandWithMaxNegativeOffset);

私が得ているエラー-

 The method get(int) is undefined for the type Queue<Command>
4

1 に答える 1

10

以下のリストスレッドを安全にするにはどうすればよいですか?LinkedListの代わりにここで使用する必要がある他のオプションはありますか?

ConcurrentLinkedQueueは、同時リンクされたキューです。javadocsから引用するには:

リンクされたノードに基づく無制限のスレッドセーフキュー。このキューは要素FIFO(先入れ先出し)を注文します。キューの先頭は、キューに最も長く存在している要素です。キューの末尾は、キューに最も短い時間存在した要素です。新しい要素はキューの末尾に挿入され、キュー取得操作はキューの先頭にある要素を取得します。ConcurrentLinkedQueueは、多くのスレッドが共通のコレクションへのアクセスを共有する場合に適切な選択です。このキューはnull要素を許可しません。

したがって、次のようなことを行います。

 Queue<Command> concurrentQueue = new ConcurrentLinkedQueue<Command>();
 Command command = new Command();
 ...
 concurrentQueue.add(command);

Listを使用して現在をラップすることもできますCollections.synchronizedList(...)。これを行うか使用ConcurrentLinkedQueueするかは、コレクションに必要なパフォーマンスの高さによって異なります。

// turn the commands list into a synchronized list by wrapping it
commands = Collections.synchronizedList(commands);

このキューの使用方法についてさらに情報を提供すると、適切なJDK同時収集に関してさらに多くの代替手段を提供できる可能性があります。

Collections.synchronizedList(commands.add(command));

質問を編集して、上記のコードについて質問しました。List.add(...)ブール値を返すため、コンパイルされません。

于 2012-08-20T19:36:46.543 に答える