import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable{
private final BlockingQueue<String> queue;
private Random r = new Random();
public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
queue.put(produce());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private String produce(){
String str = "生产: " + r.nextInt(1000);
System.out.println(str);
return str;
}
}
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable{
private BlockingQueue<String> queue;
public Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while(true){
consume(queue.take());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void consume(String str){
System.out.println("消费" + str);
}
}
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Setup {
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Producer(queue));
exec.execute(new Consumer(queue));
}
}