我编写了代码来实现生产者-消费者问题,它似乎工作正常,不需要同步。有可能吗?
我如何测试代码并检查它是否真的工作正常?我怎么知道是否会发生死锁?现在,我没有打破循环(即生产者不断插入,消费者不断地在无限循环中消费)。我使用大小为 3 的循环队列(为简单起见)作为共享资源。
这是我的代码:
import java.util.*;
public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;
public static void main(String[] args)
{
QforPC qObject=new QforPC();
//These create 2 different objects! Each object has it's own thread of execution.
//Synchronization is needed when 2 threads use the same object
new PCImpl("Producer",qObject);
new PCImpl("Consumer",qObject);
}
PCImpl(String name,QforPC qObj)
{
this.qObj=qObj;
t=new Thread(this,name);
t.start();
}
public void run()
{
if(Thread.currentThread().getName().equals("Producer"))
{
while(true)
{
Random rgen=new Random();
int n=rgen.nextInt(100);
if(n!=0)
qObj.Producer(n);
try
{
Thread.sleep(200);
}
catch(InterruptedException e)
{
}
}
}
if(Thread.currentThread().getName().equals("Consumer"))
{
while(true)
{
try
{
Thread.sleep(1500);
}
catch(InterruptedException e)
{
}
qObj.Consumer();
}
}
}
}
public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
public void Producer(int item)
{
if(r!=q.length && canProducer())
{
q[r]=item;
System.out.println("The item inserted into the queue is:"+ item);
r++;
}
if(r==q.length && f>0)
r=0;
else if(r==q.length && f==q.length)
{
r=0;
f=0;
}
}
public void Consumer()
{
int item;
System.out.println("The value of isQueue empty is:"+ isEmpty());
if(f!=q.length && isEmpty()==false)
{
System.out.println("Entered the consumer method");
item=q[f];
System.out.println("The item fetched from the queue is:"+item);
q[f]=0;
f++;
}
if(f==q.length && r<f)
f=0;
}
public boolean isEmpty()
{
for(int k=0;k<q.length;k++)
{
if(q[k]==0 && k==q.length-1)
return true;
}
return false;
}
public boolean canProducer()
{
for(int k=0;k<q.length;k++)
{
if(q[k]==0)
return true;
}
return false;
}
}