2017-02-22 92 views
-4

我在Java程序中實現推薦算法。如何在java中使用輸入值進行並行編程

但是,我有嚴重的問題。數據集太大,計算速度太慢。所以,我需要在Java中進行並行編程。

例如,

for (int i=0; i < 10000000 ; i++) { ~~~ } 

我想這個句子拆分,如

process 1: for (int i=0; i < 10000 ; i++) 

process 2: for (int i=10001; i < 20000 ; i++) 

process 3: for (int i=20001; i < 30000 ; i++) 

...

我知道類似的方法in Python。如何在Java中進行並行編程?

+3

你的意思是線程得到它?並行編程時不是並行編程?就像配對編程..但平行!只需使用Java線程 –

+0

您可以考慮使用Java 8的並行流.... –

回答

0

希望這會對你有所幫助。

public class MyRunnable implements Runnable { 
     private final long countUntil; 

     MyRunnable(long countUntil) { 
       this.countUntil = countUntil; 
     } 

     @Override 
     public void run() { 
       long sum = 0; 
       for (long i = 1; i < countUntil; i++) { 
         sum += i; 
       } 
       System.out.println(sum); 
     } 
} 



public class Main { 

     public static void main(String[] args) { 
       // We will store the threads so that we can check if they are done 
       List<Thread> threads = new ArrayList<Thread>(); 
       // We will create 500 threads 
       for (int i = 0; i < 500; i++) { 
         Runnable task = new MyRunnable(10000000L + i); 
         Thread worker = new Thread(task); 
         // We can set the name of the thread 
         worker.setName(String.valueOf(i)); 
         // Start the thread, never call method run() direct 
         worker.start(); 
         // Remember the thread for later usage 
         threads.add(worker); 
       } 
       int running = 0; 
       do { 
         running = 0; 
         for (Thread thread : threads) { 
           if (thread.isAlive()) { 
             running++; 
           } 
         } 
         System.out.println("We have " + running + " running threads. "); 
       } while (running > 0); 

     } 
} 

我從here