java 线程续篇

  • Post author:
  • Post category:java


案例

放在锁外

可冲入锁

区别

package com.udp.thread;

//生产者 消费者 容器
public class TestGuan{
    public static void main(String[] args) {
        Productor productor = new Productor(new Container());
        Consumers consumers = new Consumers(new Container());
        productor.start();
        consumers.start();
    }
}
class Chicken {
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

//生产者
class Productor extends Thread {
    Container container;
    public Productor(Container container) {
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println( "生产了第" + i + "只鸡");
        }
    }
}

//消费者
class Consumers extends Thread {
    Container container;
    public Consumers(Container container) {
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第" + container.consumption().id  + "只鸡");
        }
    }
}

//容器
class Container {
    int count = 0;
    Chicken[] chickens = new Chicken[10];

    //生产者放入鸡
    public synchronized void push(Chicken chicken) {
        //判断是否满了
        if (count == chickens.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //没满继续添加
        chickens[count] = chicken;
        count++;
        this.notifyAll();
    }

    //消费者消费了多少只鸡
    public synchronized Chicken consumption() {
        //判断是否有鸡 没有通知生产者生产
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //消费者消费
        count--;
        Chicken chicken = chickens[count];
        this.notifyAll();
        return chicken;

    }

}

线程池



版权声明:本文为l2636908832iu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。