一、管程法——通过缓冲区解决
public class TestPC {
public static void main(String[] args) {
SyContainer syContainer = new SyContainer();
new Productor(syContainer).start();
new Consumer(syContainer).start();
}
}
class Productor extends Thread{
//容器,及缓冲区
SyContainer container;
public Productor(SyContainer container){
this.container = container;
}
//生产100知鸡
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产鸡的编号"+i);
container.push(new Chicken(i));
}
}
}
class Consumer extends Thread{
//容器,及缓冲区
SyContainer container;
public Consumer(SyContainer container){
this.container = container;
}
@Override
public void run() {
for (int j = 0; j < 10; j++) {
System.out.println("消费了鸡的编号->"+container.pull().id);
}
}
}
class Chicken {
int id;//产品编号
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SyContainer {
//设置一个容器大小
Chicken[] chickens = new Chicken[10];
int count = 0; //容器计数器
//生产者放入产品
public synchronized void push(Chicken newc){
if(chickens.length==count){
//通知消费者消费,缓冲器已满
//生产登台
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要生成商品
chickens[count]=newc;
count++;
//通知消费者可以消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pull(){
if(count==0){
//消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费
count--;
Chicken eatc = chickens[count];
this.notifyAll();
return eatc;
}
}
二、信号灯法——通过标志位解决
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2==0){
this.tv.play("节目");
}
else {
this.tv.play("广告");
}
}
}
}
//观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
class TV{
String voice;//节目
boolean flag = true;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了-》"+voice);
this.voice = voice;
this.notifyAll();
this.flag = !this.flag;//新节目已出
}
//观看
public synchronized void watch(){
if (flag) {
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了-》" + voice);
this.notifyAll();
this.flag=!this.flag;//节目已经被观看
}
}