م.امید
پنج شنبه 30 آبان 1392, 11:38 صبح
با سلام.من برنامه ای نوشته ام که قرار است در آن دو thread به عنوان تولید کننده و مصرف کننده اجرا شوند و یک صف حلقوی که یک آرایه است با طول 5.تولید کننده باید مقدار تصادفی بین صفر تا صد را تولید و در صف قرار دهد.مصرف کننده هم باید از صف مصرف کند.اما برنامه درست کار نمی کند و خروجی های اشتباه می دهد.لطفا در صورت یافتن مشکل راهنمایی کنید.
public class Main {
public static final int BUFFER_SIZE = 5;
public static Integer[] buffer = new Integer[BUFFER_SIZE];
public static int rear = BUFFER_SIZE - 1;
public static int front = BUFFER_SIZE - 1;
public static void main(String[] args) throws InterruptedException {
Consumer c = new Consumer();
c.start();
Producer p = new Producer();
p.start();
}
}
class Consumer extends Thread {
@Override
public void run() {
while (true) {
synchronized (Main.buffer) {
if (Main.front == Main.rear) {
System.out.println("queue is empty");
}
else {
Main.front = (++Main.front % Main.BUFFER_SIZE);
System.out.println("Consumer state: " + "RUNNING and consume:" + Main.buffer[Main.front]);
}
}
/*try {
}
catch (Exception e) {
e.printStackTrace();
}*/
}
}
}
class Producer extends Thread {
Random randomGenerator = new Random();
@Override
public void run() {
while (true) {
synchronized (Main.buffer) {
if (Main.front == (++Main.rear % Main.BUFFER_SIZE)) {
System.out.println("full");
}
else {
Main.rear = (++Main.rear % Main.BUFFER_SIZE);
Main.buffer[Main.rear] = randomGenerator.nextInt(100);
//Main.in = ++Main.in % 5;
System.out.println("Producer state: " + "RUNNING and produce:" + Main.buffer[Main.rear]);
}
}
/*try {
}
catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
}
public class Main {
public static final int BUFFER_SIZE = 5;
public static Integer[] buffer = new Integer[BUFFER_SIZE];
public static int rear = BUFFER_SIZE - 1;
public static int front = BUFFER_SIZE - 1;
public static void main(String[] args) throws InterruptedException {
Consumer c = new Consumer();
c.start();
Producer p = new Producer();
p.start();
}
}
class Consumer extends Thread {
@Override
public void run() {
while (true) {
synchronized (Main.buffer) {
if (Main.front == Main.rear) {
System.out.println("queue is empty");
}
else {
Main.front = (++Main.front % Main.BUFFER_SIZE);
System.out.println("Consumer state: " + "RUNNING and consume:" + Main.buffer[Main.front]);
}
}
/*try {
}
catch (Exception e) {
e.printStackTrace();
}*/
}
}
}
class Producer extends Thread {
Random randomGenerator = new Random();
@Override
public void run() {
while (true) {
synchronized (Main.buffer) {
if (Main.front == (++Main.rear % Main.BUFFER_SIZE)) {
System.out.println("full");
}
else {
Main.rear = (++Main.rear % Main.BUFFER_SIZE);
Main.buffer[Main.rear] = randomGenerator.nextInt(100);
//Main.in = ++Main.in % 5;
System.out.println("Producer state: " + "RUNNING and produce:" + Main.buffer[Main.rear]);
}
}
/*try {
}
catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
}