生产者:
package test.a;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
for(int i=0;i<10;i++){
consume(queue.take());
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
void consume(Object x) {
System.out.println(x);
}
}
消费者:
package test.a;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
for(int i=0;i<10;i++){
queue.put(produce(i));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
Object produce(int i) throws InterruptedException {
return "queue"+i;
}
}
package test.a;
// new Thread(c1).start();