자바 에서 차단 대기 열 시 뮬 레이 션 (다 중 스 레 드)

5862 단어 자바
블록 대기 열 을 모 의 합 니 다. 이 대기 열 이 가득 차 면 요 소 를 추가 하면 그곳 에 막 힙 니 다. 요 소 를 꺼 낼 때 까지 추가 할 수 있 습 니 다. 요 소 를 찾 을 때 대기 열 이 비어 있 을 때 요소 가 추 가 될 때 까지 차단 합 니 다.
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
/**
 *   Queue
 * @author    
 *
 */
public class MyQueue {

    private final LinkedList list = new LinkedList();

    private final AtomicInteger count = new AtomicInteger(0);

    private final int maxSize;
    private final int minSize = 0;

    private final Object lock = new Object();

    public MyQueue (int maxSize){
        this.maxSize = maxSize;
    }

    public void put (Object obj) {
        synchronized(lock){
            while(count.get() == maxSize){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(obj);
            count.getAndIncrement();
            System.out.println("    " + obj + "     ");
            lock.notify();

        }
    }

    public Object take(){
        Object temp = null;
        synchronized (lock) {
            while(count.get() == minSize){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count.getAndDecrement();
            temp = list.removeFirst();
            System.out.println("    " + temp + "     ");
            lock.notify();
        }
        return temp;
    }

    public int size(){
        return count.get();
    }


    public static void main(String[] args) throws Exception {

        final MyQueue m = new MyQueue(5);
        m.put("a");
        m.put("b");
        m.put("c");
        m.put("d");
        m.put("e");
        System.out.println("      :" + m.size());
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                m.put("h");
                m.put("i");
            }
        }, "t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Object t1 = m.take();
                    //System.out.println("       :" + t1);
                    Thread.sleep(1000);
                    Object t2 = m.take();
                    //System.out.println("       :" + t2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t2");

        t1.start();
        Thread.sleep(1000);
        t2.start();

    }



}

좋은 웹페이지 즐겨찾기