# Thread: Sum of primes have some trouble!

1. Member Join Date
Apr 2012
Posts
5
Rep Power
0

## Sum of primes have some trouble!

Java Code:
```class Primes extends Thread {

int threadie;
static int a = 0;
static int b = 0;
static long s1 = 0;
static long s2 = 0;

public Primes(int threadID) {
threadie = threadID;

}

@Override
public void run() {
int n = 1000000;
int c = 2 * n / 3;
//int a = 0;
//int b = 0;

for (int i = 1000; i < n; i++) {
if (threadie == 1) {

if (i < c) {
if ((Primes.isPrime(i))) {
a++;
s1 += i;
//System.out.println(i);
}
}
}

if (threadie == 2) {
if (i >= c) {
if ((Primes.isPrime(i))) {
b++;
s2 += i;
//System.out.println(i);
}
}
}
}

if (threadie == 1) {
System.out.println("Thread " + threadie + " contains " + a + " prime numbers ");
}
if (threadie == 2) {
System.out.println("Thread " + threadie + " contains " + b + " prime numbers ");
}
//     int NumPrimes = a + b;
//      System.out.println(" Number of primes is: " + NumPrimes);
}

static boolean isPrime(long n) {
if (n == 2) {
return true;
}
if (n < 2 || n % 2 == 0) {
return false;
}
for (long i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] arg) {

Thread th1 = new Primes(1);
Thread th2 = new Primes(2);
th1.start();
th2.start();
try {
th1.join();
} catch (InterruptedException ie) {
}
try {
th2.join();
} catch (InterruptedException ie) {
}

System.out.println("\nThreads 1 and 2 have finished");
int NumPrimes = a + b;
long Sum = s1 + s2;
System.out.println(" Number of primes is: " + NumPrimes);
System.out.println(" Sum of primes is: " + Sum);
}
}```
I wanna 1 thread for finder primes and 1 thread for adder primes but my code can't work Main program
Java Code:
```public class Main extends Thread {

public static void main(String[] args) {
StackData data = new StackData();
Thread PrimeFinderThread = new Thread(new PrimeFinder(1000, 1000000, data));
Thread AdderThread = new Thread(new Adder(data));
PrimeFinderThread.start();
AdderThread.start();
}
}
class Adder implements Runnable {

//Thread runner;
StackData data = null;
long Sum = 0;

public Adder(StackData _data) {
data = _data;
}

public void run() {
while (true) {
Sum += data.get();
}
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
class PrimeFinder implements Runnable {

int start = 0;
int end = 0;
StackData data = null;

public PrimeFinder(int _start, int _end, StackData _data) {
start = _start;
end = _end;
data = _data;
}

@Override
public void run() {
for (int n = start; n <= end; n++) {
if (isPrime(n)) {
data.put(n);
}
}
}

public static boolean isPrime(int num) {
int limit = (int) Math.sqrt(num);

for (int i = 2; i <= limit; i++) {
if (num % i == 0) {
return false;
}

}
return true;
}
}```
StackData
Java Code:
```import java.util.Stack;

public class StackData {
private Stack<Integer> storage = new Stack<Integer>();
private boolean available = false;

public synchronized int get() {
while (available == false) {
try {
wait
} catch (InterruptedException e) { }
}
int gotdata = storage.pop();
if (storage.isEmpty()) available = false;
notifyAll();
return gotdata;
}

public synchronized void put(int value) {
storage.push(value);
available = true;
notifyAll();
}
}```
thanks a lot ^^
Last edited by banglc11; 04-26-2012 at 11:24 AM. 2. Senior Member Join Date
Apr 2012
Location
New York State of Confusion, USA
Posts
137
Blog Entries
1
Rep Power
0

## Re: Sum of primes have some trouble!

Please provide more detail about how it is not working correctly. 3. Member Join Date
Apr 2012
Posts
5
Rep Power
0

## Re: Sum of primes have some trouble!

Exercises: Using multithreading and synchronized in java to find and sum primes. 1 thread for finding primes and 1 thread for sum primes.
array n = 1000000;
Sum of prime is?  4. Senior Member Join Date
Apr 2012
Location
New York State of Confusion, USA
Posts
137
Blog Entries
1
Rep Power
0

## Re: Sum of primes have some trouble!

Your code doesn't even compile correctly does it? You StackData class's get method has a problem in it. 5. Senior Member Join Date
Apr 2012
Location
New York State of Confusion, USA
Posts
137
Blog Entries
1
Rep Power
0

## Re: Sum of primes have some trouble!

OK, I decided that I would try to run your program after I fixed the compile error for myself (I will leave it to you to figure out what was wrong).

I also added some System.out.println calls to tell me when a prime was found and, when the sum got changed, what prime was added and what the new sum is. The program worked very nicely. The only problem is that it never stops after it finds and adds all the primes. You have to figure out how to know that the PrimeFinderThread and AdderThread have completed their tasks and what the final sum is so you can print it out in your main method.

One other issue you need to handle. The number '1' is not a prime. 6. Member Join Date
Apr 2012
Posts
5
Rep Power
0

## Re: Sum of primes have some trouble! Originally Posted by jlczuk OK, I decided that I would try to run your program after I fixed the compile error for myself (I will leave it to you to figure out what was wrong).

I also added some System.out.println calls to tell me when a prime was found and, when the sum got changed, what prime was added and what the new sum is. The program worked very nicely. The only problem is that it never stops after it finds and adds all the primes. You have to figure out how to know that the PrimeFinderThread and AdderThread have completed their tasks and what the final sum is so you can print it out in your main method.

One other issue you need to handle. The number '1' is not a prime.
Thanks you ^^

Insert "Break" where to stop program?
Last edited by banglc11; 04-27-2012 at 10:45 AM. 7. Senior Member Join Date
Apr 2012
Location
New York State of Confusion, USA
Posts
137
Blog Entries
1
Rep Power
0

## Re: Sum of primes have some trouble!

No, that won't do it. You need to read the Processes and Threads Tutorial and learn how to control threads. 8. Member Join Date
Apr 2012
Posts
5
Rep Power
0

## Re: Sum of primes have some trouble!

hi, i'm a newbie java.
I do it based on the sample exercises. My yahoo artbc11 nice too meet you, jlczuk 9. Member Join Date
Apr 2012
Posts
5
Rep Power
0

## Re: Sum of primes have some trouble!

I've edited the code and the program has stopped after it finds and adds all the primes. Maybe it's not high performance.
Main()
Java Code:
```/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SumOfPrimes;

/**
* Sinh Vien: 09520740 Le Cong Bang
*
*/
public class Main {

public static void main(String[] args) {

Synchronized data = new Synchronized();
Primes primes = new Primes(1000, 1000000, data);
Adder adder = new Adder(data);
primes.start();
adder.start();
}
}```
Primes()
Java Code:
```/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SumOfPrimes;

/**
*
* @author ARS
*/
public class Primes extends Thread {

private int start, end;
private Synchronized data;

public int getStart() {
return start;
}

public void setStart(int _start) {
start = _start;
}

public int getEnd() {
return end;
}

public void setEnd(int _end) {
end = _end;
}

public Primes() {
start = 0;
end = 0;
data = null;
}

public Primes(int _start, int _end, Synchronized _data) {
start = _start;
end = _end;
data = _data;
}

static boolean isPrime(long n) {
if (n == 2) {
return true;
}
if (n < 2 || n % 2 == 0) {
return false;
}
for (long i = 3; i * i <= n; i += 2) {// i tăng lên 2 lần vì tất cả các số chẳn đều không là số nguyên tố trừ số 2.
if (n % i == 0) {
return false;
}
}
return true;
}

public void run() {
for (int n = start; n <= end; ++n) {
if (isPrime(n)) {
data.setData(n);
}
}
}
}```
Adder
Java Code:
```/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SumOfPrimes;

/**
*
* @author ARS
*/
public class Adder extends Thread {

Synchronized data = null;

long sum = 0;

public Adder(Synchronized _data)
{
data = _data;
}

@Override
public void run()
{
for(int i = 0;i<78330;i++)// Number of primes is: 78330
{
sum += data.getData();
//System.out.printf("Tong cac so nguyen to tim duoc: %d\n", sum);
}
System.out.printf("Sum of primes is: %d\n", sum);
}
}```
Synchonized()

Java Code:
```/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SumOfPrimes;

import java.util.Stack;

/**
*
* @author ARS
*/
public class Synchronized {

private Stack<Integer> data = new Stack<>();
private boolean check = false;

public synchronized int getData() {
while (check == false) {
try {
wait();
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
}

int getData = data.pop();
if (data.isEmpty()) {
check = false;
}
notifyAll();

return getData;
}

public synchronized void setData(int n) {
data.push(n);
check = true;
notifyAll();
}
}``` 10. Senior Member Join Date
Apr 2012
Location
New York State of Confusion, USA
Posts
137
Blog Entries
1
Rep Power
0

## Re: Sum of primes have some trouble!

Your threads' run() methods no longer have while(true) so they should end, but they may not. The Syncrhonized.getData() has an untimed wait() call. It will not wake up from that wait until it receives a notify. I think your Adder thread gets stuck waiting on it's call to getData after the last prime has already been processed.

You may want to consider having the prime thread notify the adder thread that it has completed. That way, the adder thread can exit and so will the main then. #### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•