2017-02-22 1 views
-4

Java 프로그램에서 권장 알고리즘을 구현합니다.Java에서 입력 값을 사용하여 병렬 프로그래밍을 수행하는 방법

그러나 심각한 문제가 있습니다. 데이터 세트가 너무 커서 계산이 너무 느립니다. 그래서 Java로 병렬 프로그래밍을 할 필요가 있습니다. 예를 들어

,

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

나는

내가 유사한 방법 in Python을 알고 ... 같은

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

으로이 문장을 분할 할 수 있습니다. Java로 병렬 프로그래밍을하는 방법?

+3

here에서있어? 사람들이 병렬로 코드를 작성할 때 병렬 프로그래밍이 아닌가? 그냥 쌍 프로그래밍처럼 ..하지만 병렬! 그냥 자바 스레드를 사용 –

+0

당신은 자바 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); 

     } 
} 

난 당신이 스레드를 의미

관련 문제