チューブオドメトリ
バッファを使用し、生産者と消費者をするためのバッファでの活動の数に基づいている
バッファを設定するには、3つの利点があります。
- 協力を達成するために並行スレッド
バッファーで、将来的には、生産者スレッドは個人消費の状況を管理する必要なしに、バッファデータの内側に配置する必要があり、同様に、消費者は、バッファからデータを取得する必要が扱うことができる、ではありませんパイプケースを生産する生産者を必要としています。
従って、「生産者スレッド」と論理から「消費者スレッド」の分離を達成します。 - 生産者と消費者のデカップリング
生産者と消費者は直接対処する必要はありません。 - 効率を向上させる、不均一忙しい解決
プロデューサー遅い生産データを、データがバッファがある場合、個人消費に影響を与えません。消費者が遅いデータ処理、生産者はバッファゾーン内のデータを配置し続けることができます
public class Thread01 {
public static void main(String[] agrs) {
Container container=new Container();
Productor p=new Productor(container);
consumer c=new consumer(container);
p.start();
c.start();
}
}
//生产者
class Productor extends Thread{
Container con;
public Productor(Container con) {
this.con=con;
}
public void run() {
//生产
for(int i=1;i<=100;i++) {
System.out.println("生产第:"+i+"个馒头");
con.push(new Steamedbun(i));
}
}
}
//消费者
class consumer extends Thread{
Container con;
public consumer(Container con) {
this.con=con;
}
public void run() {
//消费
for(int i=1;i<=100;i++) {
{
System.out.println("消费第:"+con.pop().id+"个馒头");
}
}
}
}
//缓冲区
class Container{
Steamedbun[] buns=new Steamedbun[10];//存储容器
int count=0;
//存储 生产
public synchronized void push(Steamedbun bun) {
//存在空间 能生产
if(count==buns.length) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
buns[count]=bun;
count++;
this.notifyAll();
}
//取
public synchronized Steamedbun pop() {
//何时能消费-->容器中是否有数据
if(count==0) {
try {
this.wait(); //生产者通知消费
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count--;
Steamedbun bun=buns[count];
this.notifyAll();
return bun;
}
}
class Steamedbun{
int id;
public Steamedbun(int id) {
this.id=id;
}
}
第二に、ライト法
交通信号と同様に、アクティビティの完了の現在の状態を決定するためにフラグを使用して
public class Thread02 {
public static void main(String[] agrs) {
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<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;
}
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) {
// TODO Auto-generated catch block
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("听到"+voice);
this.notifyAll();
this.flag=!this.flag;
}
}