管程法
package cooperation;
public class CoTest01 {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("生产-->"+i+"个馒头");
container.push(new Steamedbun(i));
}
}
}
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("消费-->"+container.pop().id+"个馒头");
}
}
}
class SynContainer{
Steamedbun[] buns=new Steamedbun[10];
int count=0;
public synchronized void push(Steamedbun bun) {
if(count==buns.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buns[count]=bun;
count++;
this.notifyAll();
}
public synchronized Steamedbun pop() {
if(count==0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Steamedbun bun=buns[count];
this.notifyAll();
return bun;
}
}
class Steamedbun{
int id;
public Steamedbun(int id) {
this.id = id;
}
}
信号灯法
package cooperation;
public class CoTest02 {
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;
}
public void run() {
for(int i=0;i<100;i++) {
if(i%20==0) {
this.tv.paly("奇葩说");
}else {
this.tv.paly("太污了");
}
}
}
}
class Watcher extends Thread{
Tv tv;
public Watcher(Tv tv) {
this.tv = tv;
}
public void run() {
for(int i=0;i<20;i++) {
tv.watch();
}
}
}
class Tv{
String voice;
boolean flag=true;
public synchronized void paly(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;
}
}