生产者和消费者模式
生产者 生产数据到队列中,消费者从队列中取出数据并消费 关键字synchronized对数据加锁,用Object原生的wait()和notify()做同步
Java 代码
import java. util. LinkedList;
import java. util. Queue;
public class ProducerAndConsumer {
private final int MAX_LEN= 10 ;
private Queue< Integer> queue= new LinkedList < > ( ) ;
class Producer extends Thread
{
@Override
public void run ( ) {
producer ( ) ;
}
public void producer ( ) {
while ( true ) {
synchronized ( queue) {
while ( queue. size ( ) == MAX_LEN)
{
System. out. println ( "当前队列已满" ) ;
queue. notify ( ) ;
try {
queue. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
queue. offer ( 1 ) ;
queue. notify ( ) ;
System. out. println ( "生产者生产一条消息,当前队列长度为: " + queue. size ( ) ) ;
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
}
}
}
}
}
class Consumer extends Thread
{
@Override
public void run ( ) {
consumer ( ) ;
}
public void consumer ( )
{
while ( true ) {
synchronized ( queue) {
while ( queue. isEmpty ( ) )
{
System. out. println ( "当前队列已空" ) ;
queue. notify ( ) ;
try {
queue. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
queue. poll ( ) ;
queue. notify ( ) ;
System. out. println ( "消费者消费一条消息,当前队列长度为: " + queue. size ( ) ) ;
try {
Thread. sleep ( 500 ) ;
} catch ( InterruptedException e) {
}
}
}
}
}
public static void main ( String[ ] args) {
ProducerAndConsumer pc= new ProducerAndConsumer ( ) ;
Producer producer = pc. new Producer ( ) ;
Consumer consumer = pc. new Consumer ( ) ;
producer. start ( ) ;
consumer. start ( ) ;
}
}
结果
生产者生产一条消息,当前队列长度为: 1
生产者生产一条消息,当前队列长度为: 2
生产者生产一条消息,当前队列长度为: 3
生产者生产一条消息,当前队列长度为: 4
生产者生产一条消息,当前队列长度为: 5
生产者生产一条消息,当前队列长度为: 6
生产者生产一条消息,当前队列长度为: 7
消费者消费一条消息,当前队列长度为: 6
消费者消费一条消息,当前队列长度为: 5
消费者消费一条消息,当前队列长度为: 4
消费者消费一条消息,当前队列长度为: 3
消费者消费一条消息,当前队列长度为: 2
消费者消费一条消息,当前队列长度为: 1
消费者消费一条消息,当前队列长度为: 0
当前队列已空
生产者生产一条消息,当前队列长度为: 1
生产者生产一条消息,当前队列长度为: 2
生产者生产一条消息,当前队列长度为: 3
消费者消费一条消息,当前队列长度为: 2