/** * 主線程類 * @author Leon * */ public class LimitMain { public static void main( String[] args ) { //發送請求數 int request = 10; //實例化緩存類,傳入允許幷發數 LimitBuffer sharedLocation = new LimitBuffer(3); //創建線程池 ExecutorService application = Executors.newCachedThreadPool(); //幷發線程 for(int i = 1; i <= request; i++){ application.execute( new RequestThread( sharedLocation, i ) ); } //關閉線程池 application.shutdown(); } } /** * 請求線程類 * @author Leon * */ public class RequestThread implements Runnable { private final static Random generator = new Random(); private final Buffer sharedLocation; //緩存類 private final int requestCount; //請求序號 public RequestThread( Buffer shared, int requestCount ) { this.sharedLocation = shared; this.requestCount = requestCount; } public void run() { try { //發送請求 sharedLocation.request( requestCount ); //執行過程... Thread.sleep( generator.nextInt( 5000 ) ); //結束請求 sharedLocation.response( requestCount ); } catch ( InterruptedException exception ) { exception.printStackTrace(); } } } /** * 緩存接口 * @author Leon * */ public interface Buffer { /** * 發送請求(啟動線程) * @param requestCount * @throws InterruptedException */ public void request( int requestCount ) throws InterruptedException; /** * 響應請求(結束線程) * @param requestCount * @throws InterruptedException */ public void response( int requestCount ) throws InterruptedException; } /** * 緩存實現類 * @author Leon * */ public class LimitBuffer implements Buffer { private final int[] buffer; private int occupiedCells = 0; public LimitBuffer(int count) { buffer = new int[count]; } public synchronized void request( int requestCount ) throws InterruptedException { while ( occupiedCells == buffer.length ) { System.out.println("第"+requestCount+"個請求被拒絕,原因:幷發請求數達到上限"); wait(); //等待 } System.out.println("第"+requestCount+"個請求被允許"); //佔用緩存中的一個位置 ++occupiedCells; } public synchronized void response( int requestCount ) throws InterruptedException { System.out.println("第"+requestCount+"個請求結束"); //釋放緩存中的一個位置 --occupiedCells; //喚醒線程 notify(); } }