我用synchronized
和busy waiting
写了这个java代码,但我不知道它为什么不能正常工作!例如,我得到这个输出
produced:6
produced:7
consumed:0
consumed:0
如何生产6和7但消耗0 ???我不知道它有什么问题,请帮助我,这是我的代码:
package conper;
import java.util.*;
import java.util.concurrent.TimeUnit;
class Queue<Integer> {
int items=0;
int q=0;
public int[] array= new int[10];
Queue(int i) {
}
public boolean isEmpty(){
if (this.q > 0)
{
return false ;
}else{
return true ;}
}
public boolean isFull(){
if (this.q > 10)
{
return true ;
}else{
return false ;
}
}
public int size(){
return items;
}
public synchronized void add(int x){
if(!isFull()){
array[++q]=x;
}
}
public synchronized void remove(int x){
if(!isEmpty()){
array[--q]=x;
}
}
}
class Producer implements Runnable {
private Random random = new Random();
private Queue<Integer> queue;
private boolean working = true;
public Producer(Queue<Integer> q) {
queue = q;
}
public void run() {
int product=0;
int loop = random.nextInt(10) + 20;
for (int i = 0; i < loop; i++) {
double h = Math.pow(2, Math.E * i);
}
while(working){
product = produce();
if(!queue.isFull() ){
break;
}
}
queue.add(product);
System.out.println("produced:"+product);
}
public void stop() {
working = false;
}
private int produce() {
int result = 0;
int loop = random.nextInt(10) + 20;
for (int i = 0; i < loop; i++) {
double h = Math.pow(2, Math.E * i);
}
result = random.nextInt(10);
return result;
}
}
class Consumer implements Runnable {
private Random rnd = new Random();
private Queue<Integer> queue;
private boolean working = true;
public Consumer(Queue<Integer> q) {
queue = q;
}
public void run() {
int product = 0;
while(working){
if(!queue.isEmpty())
break;
}
queue.remove(product);
System.out.println("consumed:"+product);
consume(product);
}
public void stop() {
working = false;
}
public void consume(int product) {
int loop = rnd.nextInt(10000) + 2000;
for (int i = 0; i < loop; i++) {
double h = Math.pow(2, Math.E * i);
}
}
}
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new Queue<Integer>(5);
Producer p1 = new Producer(queue);
Producer p2 = new Producer(queue);
Consumer c1 = new Consumer(queue);
Consumer c2 = new Consumer(queue);
Thread pt1 = new Thread(p1);
Thread pt2 = new Thread(p2);
Thread ct1 = new Thread(c1);
Thread ct2 = new Thread(c2);
pt1.start();
pt2.start();
ct1.start();
ct2.start();
try {
TimeUnit.MILLISECONDS.sleep(200);
p1.stop();
p2.stop();
c1.stop();
c2.stop();
}
catch (Exception e) {
return;
}
}
}
任何建议?
答案 0 :(得分:1)
您的消费者代码为
int product = 0;
// code which doesn't change "product"
System.out.println("consumed:"+product);
我建议您需要一个remove()方法,返回队列中的值而不是传递值。
我还建议您在尝试在多个线程中使用之前,让代码在一个线程中工作。