I have a program that uses two threads, one that adds some numbers and the other takes the sum and finds the average. I used a blocking queue to pass the sum to the other string. I have no problem queue.put() to put the total in the queue and then using queue.take() to take it out and print it. What I need to do though is when taking the total out of the queue is to save it to a variable so I can calculate the average with it. Can someone tell me if I am able to do this with queue.take() or if i have to use some other way. When attempt to save it to the sum variable which is an int I get the error
incompatible types
int sum = queue.take();
^
required: int
found: Object.
My code is below
import java.util.concurrent.*;
import java.util.*;
import java.util.Scanner;
class Producer implements Runnable{
protected BlockingQueue queue = null;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
Scanner input = new Scanner(System.in);
int total = 0;
int grade;
int average;
int counter = 0;
while (counter < 5){
System.out.println("Enter number: ");
grade = input.nextInt();
total = total + grade;
counter++;
}
queue.put(total);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
protected BlockingQueue queue = null;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
//System.out.println(queue.take());
int sum = queue.take();
System.out.println("The sum is "+sum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class apples {
public static void main(String[] args) throws Exception {
// BlockingQueue queue = new ArrayBlockingQueue<string>(1024);
BlockingQueue queue = new ArrayBlockingQueue(1024);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(4000);
}
}