1、基于wait和notify的实现
import java.util.concurrent.*;
class Consumer implements Runnable{
public void run(){
try{
while(!Thread.interrupted()){
synchronized(this){
while(Meal.meal==null)
wait();
}
TimeUnit.MILLISECONDS.sleep(1000);
System.out.println("other.Consumer " + Meal.meal.id);
TimeUnit.MILLISECONDS.sleep(1000);
synchronized (Meal.producer){
Meal.meal = null;
Meal.producer.notifyAll();
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class Producer implements Runnable{
public void run(){
try{
while(!Thread.interrupted()){
synchronized (this){
while(Meal.meal!=null)
wait();
}
synchronized (Meal.consumer){
Meal.meal = new Meal();
System.out.println("other.Producer " + Meal.meal.id);
Meal.consumer.notifyAll();
}
TimeUnit.MILLISECONDS.sleep(1000);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class Meal {
public static int c = 0;
public int id = c++;
public static ExecutorService exe = new ThreadPoolExecutor(5,5,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),new ThreadPoolExecutor.AbortPolicy());
public static final Consumer consumer = new Consumer();
public static final Producer producer = new Producer();
public static Meal meal = null;
public static void main(String[] args) throws InterruptedException {
exe.execute(consumer);
exe.execute(producer);
TimeUnit.SECONDS.sleep(10);
}
}
2、基于BlockingQueue的实现
import java.util.concurrent.*;
class Producer implements Runnable {
private BlockingQueue<Something> queue;
public Producer(BlockingQueue<Something> queue) {
this.queue = queue;
}
public void run(){
try{
while(!Thread.interrupted()){
Something s = new Something();
queue.put(s);
System.out.println("Produce " + s.toString());
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Something> queue;
public Consumer(BlockingQueue<Something> queue) {
this.queue = queue;
}
public void run(){
try{
while(!Thread.interrupted()){
Something s = queue.take();
System.out.println("Consume " + s.toString());
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class Something {
private static int c = 0;
private int id = c++;
public String toString(){
return "Something " + id;
}
}
public class BlockingQueueDemo {
public static void main(String[] args) {
BlockingQueue<Something> queue = new LinkedBlockingQueue<>();//这个使用不同的阻塞队列可看到不同的效果,但本质是相同的
new Thread(new Consumer(queue)).start();
new Thread(new Producer(queue)).start();
}
}