多线程学习之路-学习wait和notify

Posted 蜗牛超悍马

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程学习之路-学习wait和notify相关的知识,希望对你有一定的参考价值。

package threadtest;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class QueueTest01 {
    private LinkedList<Object> list = new LinkedList<Object>();
    private AtomicInteger count = new AtomicInteger(0);
    private final int minSize = 0;
    private final int maxSize;

    public QueueTest01(int maxsize) {
        this.maxSize = maxsize;
    }

    private final Object lock = new Object();

    public void put(Object obj) {
        synchronized (lock) {
            while (this.maxSize == count.get()) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            list.add(obj);
            count.incrementAndGet();
            System.out.println("新加入的元素是:" + obj);
            lock.notify();
        }
    }

    public Object take() {
        Object obj = null;
        synchronized (lock) {
            while (this.minSize == count.get()) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            obj = list.removeFirst();
            count.decrementAndGet();
            lock.notify();
        }
        return obj;
    }

    public static void main(String[] args) {
        final QueueTest01 myQueue = new QueueTest01(5);
        myQueue.put("a");
        myQueue.put("b");
        myQueue.put("c");
        myQueue.put("d");
        myQueue.put("e");
        System.out.println("当前对列的长度:" + myQueue.list.size());

        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                myQueue.put("f");
                myQueue.put("g");
            }
        }, "t1");
        t1.start();
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                Object o1 = myQueue.take();
                System.out.println("移除的元素为:" + o1);
                Object o2 = myQueue.take();
                System.out.println("移除的元素为:" + o2);
            }
        }, "t2");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t2.start();

    }
}

 

以上是关于多线程学习之路-学习wait和notify的主要内容,如果未能解决你的问题,请参考以下文章

多线程等待所有子线程执行完使用总结——wait()和notify(),join()方法

从网易的一道多线程笔试题学习wait与notify来控制线程同步

多线程学习-基础生产者消费者模型:wait(),sleep(),notify()实现

Java多线程学习——waitnotify和notifyAll

多线程学习(基础篇)

多线程学习(基础篇)