2015-04-04 160 views
1

我試着去走一個循環是這樣的:多線程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可以幫助完成這一點。

回答

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; 
    } 
} 
1

如果您使用的是Java 8,流將是最簡單的方法

users.parallelStream() 
       .forEach(u -> { u.doThis(); u.doThat(); }); 

你也可以實現Runnable接口,並創建一個ThreadExecutor。這將比上面的例子更多的代碼。

+0

Java 8是否會導致1.7版本的jar問題? – ThatGuy343 2015-04-04 04:51:28