1. 程式人生 > >多線程----簡單的生產者和消費者

多線程----簡單的生產者和消費者

一個 sum @override () ride pac .com lock --

package cn.zz;

//簡單的生產者和消費者
class Resource {
private String name;
private int count;
private boolean flag = false;

public synchronized void Set(String name) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName() + "...生產者"
+ this.name);
flag = true;
this.notify();
}

public synchronized void out() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "...消費者....."
+ this.name);
flag = false;
this.notify();
}
}

class Producer implements Runnable {
private Resource res;

public Producer(Resource res) {
this.res = res;
}

@Override
public void run() {
while (true) {
res.Set("++商品--");
}
}

}

class Consumer implements Runnable {
private Resource res;

public Consumer(Resource res) {
this.res = res;
}

@Override
public void run() {
while (true) {
res.out();
}

}

}

public class ProducerAndConsumer {
public static void main(String[] args) {
Resource res = new Resource();
Consumer con = new Consumer(res);
Producer pro = new Producer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}

}

技術分享圖片

圖上為運行時代碼 ,簡單的一對一關系,一個生產者,一個消費者,交替運行。

多線程----簡單的生產者和消費者