信号量实例

package cn.hc.sort.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;

/**
 * 信号量实例
 * Created by yhc on 2015/5/5.
 */
public class SemaphoreTest {


    private static class Connection {
        private int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }

    private static class Pool {
        private List idlePool = new ArrayList(32);
        private List usedPool = new ArrayList(32);

        private Semaphore semaphore=new Semaphore(32);

        public void init() {
            //初始化连接
            System.out.println("初始化连接池...");
            for (int i = 0; i < 32; i++) {
                Connection connection=new Connection();
                connection.setId(i);
                idlePool.add(connection);
            }
        }

        /****
         * 初始化连接
         * @return
         */
        public Connection get(){
            try{
                System.out.println("获取连接对象,连接数量:"+semaphore.availablePermits());
                semaphore.acquire();
                Connection connection= idlePool.remove(0);
                usedPool.add(connection);
                System.out.println("获取连接,id="+connection.getId());
                return connection;
            }catch(Exception e){
             e.printStackTrace();
            }
            return null;
        }

        /**
         * 释放连接
         * @param connection
         */
        public void release(Connection connection){
             try{
                 System.out.println("释放连接,可用连接数:"+semaphore.availablePermits());
                 usedPool.remove(connection);
                 idlePool.add(connection);
                 System.out.println("释放连接,id="+connection.getId());
             }catch (Exception e){
                 e.printStackTrace();
             }finally {
                 semaphore.release();
             }
        }
    }

    public static void main(String[] args) {
        SemaphoreTest semaphoreTest=new SemaphoreTest();
        final Pool pool=new SemaphoreTest.Pool();
        pool.init();

        for (int i = 0; i < 100; i++) {
           Thread thread=new Thread(new Runnable() {
               @Override
               public void run() {
                   Connection connection = pool.get();
                   //TODO 复杂的操作,加载数据...
                   try {
                       Thread.sleep(2000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }finally {
                       //释放连接
                       pool.release(connection);
                   }
               }
           });
           thread.start();
        }

        System.out.println("End");
    }
}

你可能感兴趣的:(java)