一、管程法
public class ProAndCus {
public static void main(String[] args) {
synContainer syncontainer=new synContainer();
pro pro = new pro(syncontainer);
cus cus = new cus(syncontainer);
pro.start();
cus.start();
}
}
//生产者
class pro extends Thread{
synContainer syncontainer;
public pro(synContainer syncontainer){
this.syncontainer=syncontainer;
}
@Override
public void run() {
for(int i=0;i<100;i++){
syncontainer.push( new Chicken(i));
System.out.println("生成了"+i+"只鸡");
}
}
}
//消费者
class cus extends Thread{
synContainer syncontainer;
public cus(synContainer syncontainer){
this.syncontainer=syncontainer;
}
@Override
public void run() {
for(int i=0;i<100;i++){
System.out.println("消费了"+syncontainer.pop().id+"只鸡");
}
}
}
class Chicken{
int id;
public Chicken(int id){
this.id=id;
}
}
//容器
class synContainer{
//容器大小
Chicken[] chickens=new Chicken[10];
int count=0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果满了,生产者就等待消费者消费
while(count==chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//未满,就往里面放产品
chickens[count]=chicken;
count++;
//可以通知消费者进行消费
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断是否可以消费
while(count==0){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//如果可以消费
count--;
Chicken chicken= chickens[count];
//吃完了通知生产
this.notifyAll();
return chicken;
}
}
二、信号灯法
public class PlayAndLook {
public static void main(String[] args) {
TV tv = new TV();
new Play(tv).start();
new Look(tv).start();
}
}
//演员
class Play extends Thread{
TV tv;
public Play(TV tv){
this.tv=tv;
}
@Override
public void run() {
for(int i=0;i<20;i++){
if(i%2==0){
tv.show("节目1");
}else{
tv.show("节目2");
}
}
}
}
//观众
class Look extends Thread{
TV tv;
public Look(TV tv){
this.tv=tv;
}
@Override
public void run() {
for(int i=0;i<20;i++){
tv.see();
}
}
}
//节目
class TV{
String name;
boolean flag=true;
//演员表演
public synchronized void show(String name){
//如果flag==false,演员等待
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//如果flag为真,演员表演
System.out.println("演员表演了"+name);
//提醒观众观看
this.notifyAll();
this.name=name;
this.flag=!this.flag;
}
//观众观看
public synchronized void see(){
//如果flag为真,观众等待
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//如果为假,观众观看
System.out.println("观众观看了"+name);
this.notifyAll();
this.flag=!this.flag;
}
}