我试图采用这样的for循环:
List<Object> users;
public void doSomething() {
for (Object o : users) {
// split up the for loop
// and handle chunks of the iteration
// across multiple threads
o.doThis();
o.doThat();
}
}
将迭代for(Object o: users){
分成多个线程。如何在不导致并发修改的情况下使用Java执行此操作。我的目标是将其扩展为线程池,因此List<Object> users;
中的对象越多意味着处理迭代块的线程越多。
我是多线程的新手,并且不确定java utils可以帮助实现这一目标。
答案 0 :(得分:1)
如果您使用的是java 8,那么流将是最简单的方式
users.parallelStream()
.forEach(u -> { u.doThis(); u.doThat(); } );
您还可以实现一个可运行的接口,并创建一个ThreadExecutor。这比上面的例子要多得多。
答案 1 :(得分:1)
You can use java.util.concurrent.Executors class which would assist you in executing multiple thread concurrently.
Have written a small method, which can assist your understanding.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}