我已经使用同步类编写了一些代码,它可以工作,但不是我想要的。我需要它只在缓冲区为空时才将糖果放入有界缓冲区数组中,然后put线程不会重新填充,直到缓冲区再次为空。我尝试了几件不同的东西,但似乎没有任何工作。
import java.util.Scanner;
class CandyBowl
{
private int[] buf;
private int in = 0;
private int out= 0;
private int count = 0;
private int size;
CandyBowl(int size)
{
this.size = size;
buf = new int[size];
}
synchronized public void put(int o)
{
while (count==size)
{
System.out.println("Candy bowl is full!");
try
{
wait();
}
catch(InterruptedException e){}
}
//System.out.println("put");
buf[in] = o;
++count;
in=(in+1) % size;
notifyAll();
}
synchronized public int get()
{
while (count==0)
{
System.out.println("Candy bowl is empty! Get the TA!");
try
{
wait();
}
catch(InterruptedException e){}
}
//System.out.println("get");
int ret_val = buf[out];
--count;
out=(out+1) % size;
notifyAll();
return (ret_val);
}
}
class PieceOfCandy
{
private int candy = 0;
public synchronized int getNextPiece()
{
return ++candy;
}
}
class Producer extends Thread
{
CandyBowl buf_;
PieceOfCandy piece;
Producer(CandyBowl b, PieceOfCandy kitkat)
{
buf_ = b;
piece = kitkat;
}
public void run()
{
try
{
while(true)
{
buf_.put(piece.getNextPiece());
Thread.sleep(250);
}
}
catch (InterruptedException e)
{
System.out.println("TA: I need to buy more candy!");
}
}
}
class Consumer extends Thread
{
CandyBowl buf_;
char ident;
Consumer(CandyBowl b, char id)
{
buf_ = b;
ident = id;
}
public void run()
{
try
{
int value;
while(true)
{
value = buf_.get();
System.out.println("Professor " + ident + " took candy " + value);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Professors " + ident + ": I guess I'll teach now.");
}
}
}
public class OS_BoundedBuffer
{
public static void main (String args[])
{
char id = 'A';
PieceOfCandy candy = new PieceOfCandy();
Scanner sc = new Scanner(System.in);
System.out.print("How many Professors want to think? ");
final int numProfs = sc.nextInt();
CandyBowl bowl = new CandyBowl(10);
System.out.println();
Producer teachAssist = new Producer(bowl, candy);
Consumer profs[] = new Consumer[numProfs];
for (int i = 0; i < numProfs; i++)
{
profs[i] = new Consumer(bowl, id);
id = (char)(id + '\001');
}
teachAssist.start();
for (int i = 0; i < numProfs; i++)
profs[i].start();
try
{
Thread.sleep(30000);
System.out.println("Main: I'm tired of waiting!");
for(int i = 0; i < numProfs; i++)
profs[i].interrupt();
teachAssist.interrupt();
for(int i = 0; i < numProfs; i++)
profs[i].join();
teachAssist.join();
}
catch (InterruptedException e) {}
}
}
任何帮助将不胜感激!
答案 0 :(得分:-1)
可能导致错误的一件事是您正在同步访问一个资源的两种方法。不要在方法上进行同步,而是尝试在Object
或buf
上进行同步。这是一个问题,因为多个线程正在修改count
和buf
的元素
如果需要一个例子来说明竞争条件是如何运作的,请告诉我。