线程协作
生产者 消费者
管程法
public class PC {
//管程罚
public static void main(String[] args) {
Syncontainer container=new Syncontainer();
new Producer(container).start();
new Consumer(container).start();
}
}
class Producer extends Thread{
//生产者
Syncontainer container;
public Producer(Syncontainer container){
this.container=container;
}
public void run(){
for(int i =1;i<20;i++){
System.out.println(">>>>>>>生产了第"+i+"只鸡");
container.producer(new Chicken(i));
}
}
}
class Consumer extends Thread{
//消费者
Syncontainer container;
public Consumer(Syncontainer container){
this.container=container;
}
public void run(){
for(int i =1;i<20;i++){
System.out.println("消费了第>>>>"+container.consumer().id+"只鸡");
container.consumer();
}
}
}
class Chicken{
//产品
int id;
public Chicken(int id){
this.id=id;
}
}
class Syncontainer{
//容器
//容器大小
Chicken[] chickenNumber=new Chicken[10];
int count=0;
//生产者生产
public synchronized void producer(Chicken chicken){
if(count==chickenNumber.length){
//如果容器满了 通知消费者 消费
try {
this.wait();//生产等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满 继续生产 并装进容器
chickenNumber [count++]=chicken;
//System.out.println("库存:"+count);//不能超过 容器chickenNumber.length的长度
//通知消费者 消费
this.notifyAll();
}
//消费者消费
public Chicken consumer(){
//通知 消费者 消费
System.out.println(">>>>>>>库存:"+count);
if(count==0){
//如果容器里没有了 通知 生产者 生产
try {
this.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
//消费
count--;
Chicken chicken =chickenNumber[count];
//吃完了 通知生产者 生产
this.notifyAll();
return chicken;
}
}
次处代码有误
标志法(信号灯法)
public class PC2 {
//
public static void main(String[] args) {
WatchTV TV=new WatchTV();
new Performer(TV).start();
new Audience(TV).start();
}
}
class Performer extends Thread{
//演员
WatchTV TV=new WatchTV();
Performer(WatchTV TV){
this.TV=TV;
}
public void run(){
for(int i=0;i<20;i++){
if(i%2==0){
this.TV.Perform("奔跑吧兄弟!");//正片
}
else{
this.TV.Perform("脑白金!");//广告
}
}
}
}
class Audience extends Thread{
//观众
WatchTV TV=new WatchTV();
Audience(WatchTV TV){
this.TV=TV;
}
public void run(){
for(int i=0;i<20;i++){
this.TV.watch();
}
}
}
class WatchTV{
String voice;//节目
Boolean flag=true;
public synchronized void Perform(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("电视开始表演:"+voice);
this.notifyAll();//告诉观众 看正片了
this.voice=voice;
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;
}
}