协作模型:生产者消费者实现的方式之一:管程法
public class Cotest {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
class Productor extends Thread{
SynContainer containers;
public Productor(SynContainer containers) {
super();
this.containers = containers;
}
@Override
public void run() {
for(int i=0;i<100;i++) {
System.out.println("生产第"+i+"个馒头");
containers.push(new Streamedbun(i));
}
}
}
class Consumer extends Thread{
SynContainer containers;
public Consumer(SynContainer containers) {
super();
this.containers = containers;
}
@Override
public void run() {
for(int i=0;i<100;i++) {
System.out.println("消费第"+containers.pop().getId()+"个馒头");
}
}
}
class SynContainer {
Streamedbun[] buns=new Streamedbun[10];
int count=0;
public synchronized void push(Streamedbun bun) {
if(count==buns.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buns[count]=bun;
count++;
this.notifyAll();
}
public synchronized Streamedbun pop() {
if(count==0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Streamedbun bun=buns[count];
this.notifyAll();
return bun;
}
}
class Streamedbun{
private int id;
public Streamedbun(int id) {
super();
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
协作模型:生产者消费者实现的方式之一:信号灯法
public class CoLight {
public static void main(String[] args) {
Tv tv=new Tv();
new Player(tv).start();
new Audience(tv).start();
}
}
class Player extends Thread{
Tv tv;
public Player(Tv tv) {
super();
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 Audience extends Thread{
Tv tv;
public Audience(Tv tv) {
super();
this.tv = tv;
}
@Override
public void run() {
for(int i=0;i<20;i++) {
this.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=false;
}
public synchronized void watch() {
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("听到了:"+voice);
this.notifyAll();
this.flag=true;
}
}