[英]4 thread find prime number
我嘗試使用 4 個均勻平衡的線程來查找從 10 到 30 的質數。我想知道每個線程有多少個質數,總共有多少個,並打印出質數。 我多次運行該程序,每次輸出都不同。 有人可以幫我找出問題所在。
public class Prime extends Thread
{
int thread;
static long max=30;
static long min=10;
static long[] primes = new long[100];
static int a=0;
static int b=0;
static int c=0;
static int d=0;
public Prime(int threadID)
{
thread = threadID;
}
public void run()
{
for(long i = min; i<=max; i++){
if(isPrime(i)){
if(thread ==1){
if(i<=15){
primes[a++] = i;
}
}
if(thread ==2){
if(i>15 && i <=20){
primes[b++] = i;
}
}
if(thread ==3){
if(i>20 && i<=25){
{
primes[c++] = i;
}
}
}
if(thread ==4){
if(i>25){
primes[d++] = i;
}
}
}
}
if(thread ==1){System.out.println("Thread 1 contains "+a+" prime numbers");}
if(thread ==2){System.out.println("Thread 2 contains "+b+" prime numbers");}
if(thread ==3){System.out.println("Thread 3 contains "+c+" prime numbers");}
if(thread ==4){System.out.println("Thread 4 contains "+d+" prime numbers");}
}
public static boolean isPrime(long n) {
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] arg)
{
Thread th1 = new Prime(1);
Thread th2 = new Prime(2);
Thread th3 = new Prime(3);
Thread th4 = new Prime(4);
th1.start();
th2.start();
th3.start();
th4.start();
try{th1.join();}
catch(InterruptedException ie){}
try{th2.join();}
catch(InterruptedException ie){}
try{th3.join();}
catch(InterruptedException ie){}
try{th4.join();}
catch(InterruptedException ie){}
int total = a+b+c+d;
System.out.println("Total number of prime: "+total);
for (int i=0;i<10; i++){
System.out.println(""+i+": "+Prime.primes[i]);
}
}
}
正如@Louis 在對您的問題的評論中提到的,您的所有線程都相互覆蓋。
當 Thread1 將它的工作放在 primes[0] 中時,其他線程不會被通知,然后也將它們的工作放在 primes[0] 中(覆蓋已經存在的工作)。 您得到不同的輸出主要是因為線程運行的順序是“隨機的”。
一個簡單的解決方案是不為每個線程 (a,b,c,d) 設置索引,而是使用來自java.util.concurrent.atomic.AtomicInteger
的AtomicInteger
。
如何使用AtomicInteger
簡短示例
import java.util.concurrent.atomic.AtomicInteger;
public class Prime extends Thread
{
int thread;
static long max=30;
static long min=10;
static long[] primes = new long[100];
static AtomicInteger index = new AtomicInteger(0);
public Prime(int threadID)
{
thread = threadID;
}
public void run()
{
for(long i = min; i<=max; i++){
if(isPrime(i)){
if(thread ==1){
if(i<=15){
primes[index.getAndAdd(1)] = i;
}
}
if(thread ==2){
if(i>15 && i <=20){
primes[index.getAndAdd(1)] = i;
}
}
如果您想計算每個線程使用了多少素數,那么您仍然可以使用a,b,c,d
但它們不應用作共享數據的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.