计数信号量__Demo

来源:互联网 发布:篆刻印章制作软件 编辑:程序博客网 时间:2024/05/21 11:31

Pool

package com.thread.demo2;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Semaphore;public class Pool<T>{    private int size;    private List<T> items = new ArrayList<T>();    private volatile boolean[] checkedOut;    private Semaphore available;    public Pool(Class<T> classObject, int size)    {        this.size = size;        checkedOut = new boolean[size];        available = new Semaphore(size, true);        // Load pool with objects that can be checked out:        for (int i = 0; i < size; i++)        {            try            {                // Assumes a default constructor:                items.add(classObject.newInstance());            }            catch (Exception e)            {                throw new RuntimeException(e);            }        }    }    public T checkOut()        throws InterruptedException    {        // blocking until get item.        available.acquire();        return getItem();    }    public void checkIn(T x)    {        if (releaseItem(x))            available.release();    }    public synchronized T getItem()    {        for (int i = 0; i < size; i++)            if (!checkedOut[i])            {                checkedOut[i] = true;                return items.get(i);            }        return null;// Semaphore prevents reaching here    }    public synchronized boolean releaseItem(T item)    {        int index = items.indexOf(item);        if (index == -1)            return false;// Not in the list        if (checkedOut[index])        {            checkedOut[index] = false;            return true;        }        return false;// Wasn't checked out    }}

Fat

package com.thread.demo2;public class Fat{    private volatile double d;// prevent optimization    private static int counter = 0;    private final int id = counter++;    public Fat()    {        // Expensive ,interruptible operation:        for (int i = 0; i < 10000; i++)        {            d += (Math.PI + Math.E) / (double)i;        }    }    public void operation()    {        System.out.println(this);    }    @Override    public String toString()    {        return "Fat  id = " + id + "";    }}

SemaphoreDemo

package com.thread.demo2;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;public class SemaphoreDemo{    final static int SIZE = 25;    public static void main(String[] args)        throws InterruptedException    {        final Pool<Fat> pool = new Pool<Fat>(Fat.class, SIZE);        ExecutorService exec = Executors.newCachedThreadPool();        for (int i = 0; i < SIZE; i++)        {            exec.execute(new CheckoutTask<Fat>(pool));        }        System.out.println("All checkoutTasks created");        List<Fat> list = new ArrayList<Fat>();        for (int j = 0; j < SIZE; j++)        {            Fat f = pool.checkOut();            System.out.println(j + " :main() thread checked out.");            f.operation();            list.add(f);        }        Future<?> blocked = exec.submit(new Runnable()        {            @Override            public void run()            {                try                {                    // Semaphore prevents additional checkout.so call is blocked:                    pool.checkOut();                }                catch (InterruptedException e)                {                    System.out.println("checkOut() Interrupted................");                }            }        });        TimeUnit.MILLISECONDS.sleep(2);        blocked.cancel(true);// Break out of blocked call        System.out.println("Checking in objects in " + list);        for (Fat fat : list)        {            pool.checkIn(fat);        }        for (Fat fat : list)        {            pool.checkIn(fat);// Second checkIn ignored        }        exec.shutdown();    }}class CheckoutTask<T> implements Runnable{    private static int counter = 0;    private final int id = counter++;    private Pool<T> pool;    public CheckoutTask(Pool<T> pool)    {        this.pool = pool;    }    @Override    public void run()    {        try        {            T item = pool.checkOut();            System.out.println(this + " check out " + item);            TimeUnit.MILLISECONDS.sleep(1);            System.out.println(this + " checking in " + item);            pool.checkIn(item);        }        catch (InterruptedException e)        {            e.printStackTrace();        }    }    @Override    public String toString()    {        return "CheckoutTask id = " + id;    }}
0 0
原创粉丝点击