PCCommon 生成消费公共类:
public class PCCommon {
private Queue<User> queue = new LinkedList<User>();
//生产
public synchronized void productData(){
try{
while(queue.size() == 1 ){
wait();
}
User user = new User();
Random random = new Random();
int ram = random.nextInt();
user.setUserid(ram);
user.setUsername("username:"+ram);
queue.add(user);
notifyAll();
}catch(InterruptedException e){
e.printStackTrace();
}
}
//消费
public synchronized void consumerData(){
try{
while(queue.size() == 0){
wait();
}
User user = queue.poll();
if(user != null){
System.out.println("userid:"+user.getUserid());
System.out.println("username:"+user.getUsername());
}
notifyAll();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
ProductThread 生产者线程类:
public class ProductThread extends Thread{
private PCCommon pccommon;
public ProductThread(PCCommon pccommon){
this.pccommon=pccommon;
}
@Override
public void run(){
while(true){
pccommon.productData();
}
}
}
ConsumerThread 消费者线程类:
public class ConsumerThread extends Thread{
private PCCommon pccommon;
public ConsumerThread(PCCommon pccommon){
this.pccommon=pccommon;
}
@Override
public void run(){
while(true){
pccommon.consumerData();
}
}
}
PCTest 测试:
public class PCTest {
public static void main(String[] args){
PCCommon pc = new PCCommon();
ProductThread pt = new ProductThread( pc);
ConsumerThread ct1 = new ConsumerThread(pc);
ConsumerThread ct2 = new ConsumerThread(pc);
ConsumerThread ct3 = new ConsumerThread(pc);
pt.start();
ct1.start();
ct2.start();
ct3.start();
}
}