线程通信解决生产者消费者问题
求解的过程写在注释里了
package com.gen.test;
/**
* @ClassName : CommunicationDemo
* @Author : ShiGen
* @Date: 2021/3/27 16:38
* @Description : ${description}
*/
public class CommunicationDemo {
public static void main(String[] args){
sharedResores sharedResores = new sharedResores ( );
new Consuer ( sharedResores ).start ( );
new Producer ( sharedResores ).start ( );
}
}
class sharedResores {
private char c;
// 标记还没有生产
private boolean isProduced = false;
synchronized void putShareChar(char c){
/* 没生产是因为消费者还没有消费——等待
生产了唤醒消费者消费
*/
// 没有在生产是因为在等待消费
if(isProduced){
try{
System.out.println ( "没有消费,生产者停止生产" );
wait ( );
} catch(InterruptedException e){
e.printStackTrace ( );
}
}
this.c = c;
// 已经生产了,通知消费者
isProduced = true;
notify ( );
System.out.println ( "生产了 " + c + " 消费者来消费" );
}
// 同步的方法获得当前的资源
synchronized char getShareChar( ){
if(!isProduced){
try{
System.out.println ( "生产者正在生产,等待一伙儿" );
wait ( );
} catch(InterruptedException e){
e.printStackTrace ( );
}
}
isProduced = false;
notify ( );
System.out.println ( "消费了 " + c + " 通知生产者生产" );
return this.c;
}
}
class Producer extends Thread {
private sharedResores sharedResores;
Producer(sharedResores sharedResores){
this.sharedResores = sharedResores;
}
@Override
public void run( ){
for(char ch = 'A'; ch <= 'D'; ch++){
try{
Thread.sleep ( (int) (Math.random ( ) * 3000) );
} catch(InterruptedException e){
e.printStackTrace ( );
}
sharedResores.putShareChar ( ch );
}
}
}
class Consuer extends Thread {
private sharedResores sharedResores;
Consuer(sharedResores sharedResores){
this.sharedResores = sharedResores;
}
@Override
public void run( ){
char ch = ' ';
while(ch!='D'){
try{
Thread.sleep ( (int) (Math.random ( ) * 3000) );
} catch(InterruptedException e){
e.printStackTrace ( );
}
ch = sharedResores.getShareChar ( );
}
}
}
运行的结果
生产了 A 消费者来消费
消费了 A 通知生产者生产
生产了 B 消费者来消费
消费了 B 通知生产者生产
生产了 C 消费者来消费
消费了 C 通知生产者生产
生产了 D 消费者来消费
消费了 D 通知生产者生产