package com.onecloud.og.server.driver.lumi.test;
import java.util.concurrent.BlockingQueue;
public class Custom implements Runnable{
private final BlockingQueue<Integer> sharedQueue;
public Custom(BlockingQueue<Integer> sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for(int i = 0;i<50;i++) {
try {
Thread.sleep(200);
int j = sharedQueue.take();
System.out.println(Thread.currentThread().getName()+"消费---"+j);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者类
package com.onecloud.og.server.driver.lumi.test;
import java.util.concurrent.BlockingQueue;
public class Product implements Runnable{
private final BlockingQueue<Integer> sharedQueue;
public Product(BlockingQueue<Integer> sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for(int i = 0;i<50;i++) {
try {
Thread.sleep(200);
sharedQueue.put(i);
System.out.println(Thread.currentThread().getName()+"生产---"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
main方法测试
package com.onecloud.og.server.driver.lumi.test;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class MainTest {
public static void main(String[] args) {
BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>();
Custom custom = new Custom(sharedQueue);
Product product = new Product(sharedQueue);
new Thread(custom).start();
new Thread(product).start();
}
}