And*_*rio 4 java string multithreading
我试图找出让多个线程在同一个字符串列表中工作的最佳方法.例如,假设我有一个单词列表,我想要多个线程来打印出这个列表中的每个单词.
这就是我想出的.该线程使用while循环,当迭代器具有next时,它会打印出来并从列表中删除它.
import java.util.*;
public class ThreadsExample {
static Iterator it;
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<>();
list.add("comet");
list.add("planet");
list.add("moon");
list.add("star");
list.add("asteroid");
list.add("rocket");
list.add("spaceship");
list.add("solar");
list.add("quasar");
list.add("blackhole");
it = list.iterator();
//launch three threads
RunIt rit = new RunIt();
rit.runit();
rit.runit();
rit.runit();
}
}
class RunIt implements Runnable {
public void run()
{
while (ThreadsExample.it.hasNext()) {
//Print out and remove string from the list
System.out.println(ThreadsExample.it.next());
ThreadsExample.it.remove();
}
}
public void runit() {
Thread thread = new Thread(new RunIt());
thread.start();
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎有效,虽然我Exception in thread "Thread-2" Exception in thread "Thread-0" java.lang.IllegalStateException在运行期间遇到了一些错误:
线程"Thread-1"中的异常线程"Thread-0" java.util.ArrayList中的
java.lang.IllegalStateException.Ir.remove
(ArrayList.java:864)at
RunIt.run(ThreadsExample.java:44)at
java.lang.Thread.run(Thread.java:745)
java.util.ArrayList中的java.lang.IllegalStateException $ Itr.remove(ArrayList.java:864
)at
java的RunIt.run(ThreadsExample.java:44). lang.Thread.run(Thread.java:745)
我是正确地执行此操作还是有更好的方法让多个线程在同一个字符串池上工作?
更好的方法是使用并发队列.Queue接口用于在处理结构之前保存结构中的元素.
final Queue<String> queue = new ConcurrentLinkedQueue<String>();
queue.offer("asteroid");
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.execute(new Runnable() {
public void run() {
System.out.println(queue.poll());
}
});
executorService.shutdown();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1672 次 |
| 最近记录: |