【java】100,000までの素数の数を並列処理(Thread)で求めたい
java8にて、100,000までの素数の数及び以下の内容を4つの並列処理(Thread)で求めたいです。
・素数の数の算出には近似式は用いず,繰り返し処理を用いて総当たりで求める.
・2つ以上のスレッドにより並列処理することによって,なるべく高速に結果を得るように実装する.
スレッドの概念を正しく理解できていないため、以下のコードでは4回処理を繰り返すだけの機能となってしまっておます。
並列処理の実装方法をご教授ください。
該当のソースコード
java
1public class Prog4Lec14Sub2{ 2 static Counter counter = new Counter(); 3 4 public static void main(String[] args) { 5 6 MyThread1 threads1 = new MyThread1(); 7 MyThread2 threads2 = new MyThread2(); 8 MyThread3 threads3 = new MyThread3(); 9 MyThread4 threads4 = new MyThread4(); 10 11 12 long startTime; 13 long estimatedTime; 14 15 startTime = System.nanoTime(); 16 17 threads1.start(); 18 threads2.start(); 19 threads3.start(); 20 threads4.start(); 21 22// スレッドの処理待ち 23 try { 24 threads1.join(); 25 threads2.join(); 26 threads3.join(); 27 threads4.join(); 28 } 29 catch(InterruptedException e) { 30 System.out.println(e); 31 } 32 estimatedTime = System.nanoTime() - startTime; 33 System.out.println(estimatedTime/1000 + "ns"); 34 } 35} 36
java
1public class Counter { 2 int count; 3 public void countUp() { 4 5 for(int i=2; i<100; i++) { 6 for(int j=2; i%j != 0 && j<i || j == i; j++) { 7 if(j == i) { 8 System.out.println(i + ":素数"); 9 } 10 } 11 } 12 } 13}
java
1//これを、MyThread1~4.javaまで準備 2public class MyThread1 extends Thread { 3 public void run() { 4 Prog4Lec14Sub2.counter.countUp(); 5 } 6}
回答1件
あなたの回答
tips
プレビュー