一、生产者和消费者问题
生产者消费者模式是一个十分经典的多线程协作的模式。
生产者和消费者问题包含了两类线程:一类是生产者线程用于生产数据,
一类是消费者数据用于消费数据。
public class Box { private int milk; private static boolean state = false ; public synchronized void storeMilk ( int milk) { if ( state) { try { wait ( ) ; } catch ( InterruptedException e) { e. printStackTrace ( ) ; } } this . milk = milk; System . out. println ( "生产者将第" + this . milk + "瓶奶放入奶箱中" ) ; state = true ; notify ( ) ; } public synchronized void get ( ) { if ( ! state) { try { wait ( ) ; } catch ( InterruptedException e) { e. printStackTrace ( ) ; } } System . out. println ( "消费者拿到第" + this . milk + "瓶奶" ) ; state = false ; notify ( ) ; }
} public class Producer implements Runnable { private Box b; public Producer ( Box b) { this . b = b; } @Override public void run ( ) { for ( int i = 1 ; i <= 10 ; i++ ) { b. storeMilk ( i) ; } }
} public class Customer implements Runnable { private Box b; public Customer ( Box b) { this . b = b; } @Override public void run ( ) { while ( true ) { b. get ( ) ; } }
}
public static void main ( String [ ] args) { Box box = new Box ( ) ; Producer producer = new Producer ( box) ; Customer customer = new Customer ( box) ; Thread t1 = new Thread ( producer, "生产者" ) ; Thread t2 = new Thread ( customer, "消费者" ) ; t1. start ( ) ; t2. start ( ) ; }
运行结果如下:
生产者将第1瓶奶放入奶箱中
消费者拿到第1瓶奶
生产者将第2瓶奶放入奶箱中
消费者拿到第2瓶奶
生产者将第3瓶奶放入奶箱中
消费者拿到第3瓶奶
生产者将第4瓶奶放入奶箱中
消费者拿到第4瓶奶
生产者将第5瓶奶放入奶箱中
消费者拿到第5瓶奶
生产者将第6瓶奶放入奶箱中
消费者拿到第6瓶奶
生产者将第7瓶奶放入奶箱中
消费者拿到第7瓶奶
生产者将第8瓶奶放入奶箱中
消费者拿到第8瓶奶
生产者将第9瓶奶放入奶箱中
消费者拿到第9瓶奶
生产者将第10瓶奶放入奶箱中
消费者拿到第10瓶奶