- package demo;
- public class ProducerAndConsuDemo {
- /**
- * 模拟生产者和消费者
- */
- public static void main(String[] args) {
- Resource r = new Resource();
- for(int i = 1;i<4;i++){
- new Thread(new Pro(r)).start();
- new Thread(new Consu(r)).start();
- }
- }
- }
- class Resource{
- private String name;
- private int count = 0;
- private boolean flag = false;
-
- public void produce(){
- synchronized(this){
- while(flag){
- try {
- Thread.sleep(10);
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- count++;
- System.out.println(Thread.currentThread().getName()+"...生产"+count);
- flag = flag^true;
- this.notifyAll();
- }
- }
- public void sell(){
- synchronized(this){
- while(!flag){
- try {
- Thread.sleep(50);
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName()+"...消费"+count);
- flag = flag^true;
- this.notifyAll();
- }
- }
- }
- class Pro implements Runnable{
- private Resource r;
- public Pro(Resource r) {
- super();
- this.r = r;
- }
- @Override
- public void run() {
- while(true){
- r.produce();
- }
- }
- }
- class Consu implements Runnable{
- private Resource r;
- public Consu(Resource r) {
- super();
- this.r = r;
- }
- @Override
- public void run() {
- while(true){
- r.sell();
- }
- }
- }
复制代码 |
|