신 호 량 실례

3037 단어 자바
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");
    }
}

좋은 웹페이지 즐겨찾기