运行结果图如下:
创建文件如下:
1.consumer.java文件
package com.example.wocu;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue<PCData> queue;
private static final int SLEEPTIME = 1000;
public Consumer(BlockingQueue<PCData> queue) {
this.queue = queue;
// TODO Auto-generated constructor stub
}
public void run(){
System.out.println("start Consumer id:"+Thread.currentThread().getId());
Random r = new Random();
try{
while(true){
PCData data = queue.take();
if(data != null)
{
System.out.println("消费Data:"+data.getData());
Thread.sleep(r.nextInt(SLEEPTIME));
}
}
}catch (InterruptedException e){
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
2.Producer.java文件:
package com.example.wocu;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue<PCData> queue;
private static final int SLEEPTIME = 1000;
public Consumer(BlockingQueue<PCData> queue) {
this.queue = queue;
// TODO Auto-generated constructor stub
}
public void run(){
System.out.println("start Consumer id:"+Thread.currentThread().getId());
Random r = new Random();
try{
while(true){
PCData data = queue.take();
if(data != null)
{
System.out.println("消费Data:"+data.getData());
Thread.sleep(r.nextInt(SLEEPTIME));
}
}
}catch (InterruptedException e){
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
3.PCData.文件:
package com.example.wocu;
/**
* 容器数据类型
* @author ctk
*
*/
public class PCData {
private final int intData;
public PCData(int d){
intData = d;
}
public PCData(String d){
intData = Integer.valueOf(d);
}
public int getData(){
return intData;
}
@Override
public String toString(){
return "data:"+intData;
}
}
4.main文件:
package com.example.wocu;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Test2 {
/**
* 主函数
* @author ctk
*
*/
public static void main(String[] args) throws InterruptedException {
BlockingQueue<PCData> queue=
new LinkedBlockingQueue<PCData>(100);
Producer p1 = new Producer(queue);
Producer p2 = new Producer(queue);
Producer p3 = new Producer(queue);
Consumer c1 = new Consumer(queue);
Consumer c2 = new Consumer(queue);
Consumer c3 = new Consumer(queue);
new Thread(p1).start();
new Thread(p2).start();
new Thread(p3).start();
new Thread(c1).start();
//new Thread(c2).start();
//new Thread(c3).start();
Thread.sleep(60*1000);
p1.stop();
p2.stop();
p3.stop();
Thread.sleep(3000);
}
}