java Semaphore訊號亮-允許多個任務同時訪問這個資源--thinking in java21.7.6

來源:互聯網
上載者:User

標籤:

package org.rui.thread.newc.semaphore;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Semaphore;/** * 允許N個任務同時訪問這個資源 * @author lenovo * * @param <T> */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++){// assumes a default constructor自己的預設建構函式try{//Object o=classObject.newInstance();//Fat f=(Fat) classObject.newInstance();items.add(classObject.newInstance());} catch (Exception e){throw new RuntimeException(e);}}}//如果你需要一個新對象,那麼你可以調用checkOut(),在使用完後遞交給checkIn()public T checkOut() throws InterruptedException{//如果沒有任何的Semaphore許何證,意味著池中沒有對象可用了available.acquire();//擷取一個許可(如果提供了一個)並立即返回,將可用的許可數減 1。return getItems();}public void checkIn(T x){if (releaseItem(x))//如果被簽入的對象有效,則會向訊號亮返回一個許可證available.release();//釋放一個許可,將其返回給訊號量。}private synchronized T getItems(){for (int i = 0; i < size; ++i){//System.out.println(checkedOut[i]);if (!checkedOut[i])//如果為false  說明是releaseItem 則可以簽出{checkedOut[i] = true;//System.out.println("xxxxxx===="+items.get(i));return items.get(i);}}return null;// semaphore prevents reaching here防止訊號到達這裡}private synchronized boolean releaseItem(T item){int index = items.indexOf(item);if (index == -1)return false;// not in the listif (checkedOut[index])//如果為true 則說明已簽出 則可以釋放{//System.out.println("releaseItem:"+item);checkedOut[index] = false;return true;}return false;// wasn't checked out 沒有簽出}}

package org.rui.thread.newc.semaphore;public class Fat{private volatile double d;private static int counter = 0;private final int id = counter++;public Fat(){// expensive, interruptible operation:for (int i = 1; i < 10000; i++){d += (Math.PI + Math.E) / (double) i;}}public void operation(){System.out.println("operation>>  "+this);}@Overridepublic String toString(){return "Fat>>id:" + id;}}

<pre name="code" class="java">package org.rui.thread.newc.semaphore;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;class CheckoutTask<T> implements Runnable{private static int counter = 0;private final int id = counter++;private int index;private Pool<T> pool;public CheckoutTask(Pool<T> pool, int size){this.pool = pool;this.index = size;}@Overridepublic void run(){try{T item = pool.checkOut();System.out.println(this + "checked out 已簽出:" + item);TimeUnit.SECONDS.sleep(1);System.out.println("checked in 釋放:" + item);pool.checkIn(item);// 將用完的對像釋放// System.out.println(index+"  counter="+counter+"  id=="+id);// if(index==counter-1){// TimeUnit.SECONDS.sleep(1);// System.out.println("=======all checkoutTasks created");//// }} catch (InterruptedException e){System.out.println(e.getMessage());// TODO Auto-generated catch block// e.printStackTrace();}}@Overridepublic String toString(){return "checkoutTask " + id + " ";}}// //////////////////////////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();// 開始操練poolfor (int i = 0; i < Size; i++){exec.execute(new CheckoutTask<Fat>(pool, i));}System.out.println("all checkoutTasks created");// main 開始簽出pool中的Fat對象 -1,但並不簽入他們。// 一但池中的所有的對象都被簽出後,semaphore將不在執行任何簽出操作,List<Fat> list = new ArrayList<Fat>();for (int i = 0; i < Size; i++){try{Fat f = pool.checkOut();System.out.println(i + "   >>main() thrad checked out 簽出");f.operation();list.add(f);} catch (InterruptedException e){e.printStackTrace();}}// 無對象可簽出 run 會阻塞Future<?> blocked = exec.submit(new Runnable(){@Overridepublic void run(){try{// semaphore prevents additional checkout 訊號量防止額外的校正// so call is blocked 因此調用被阻塞pool.checkOut();} catch (InterruptedException e){System.err.print("checkOut() interrupted");// e.printStackTrace();}}});// 持有一段時間後再將它們簽入TimeUnit.SECONDS.sleep(2);// 以此來掙脫future,取消,冗餘的簽入將被pool忽略System.out.println("任務是否完成:"+blocked.isDone());blocked.cancel(true);// break out of blocked call 中斷呼叫中斷 試圖取消對此任務的執行System.out.println();/////////////////都簽入之後 再可以繼續使用poolfor (Fat f : list){pool.checkIn(f);}//這裡其實可以再次使用pool了,for (Fat f : list){pool.checkIn(f);// second checkin ignored 二簽忽略}// exec.shutdown();}}/** * output: * checkoutTask 0 checked out 已簽出:Fat>>id:0checkoutTask 2 checked out 已簽出:Fat>>id:2checkoutTask 1 checked out 已簽出:Fat>>id:1checkoutTask 4 checked out 已簽出:Fat>>id:3checkoutTask 3 checked out 已簽出:Fat>>id:4checkoutTask 5 checked out 已簽出:Fat>>id:5checkoutTask 6 checked out 已簽出:Fat>>id:6checkoutTask 7 checked out 已簽出:Fat>>id:7checkoutTask 8 checked out 已簽出:Fat>>id:8checkoutTask 9 checked out 已簽出:Fat>>id:9checkoutTask 10 checked out 已簽出:Fat>>id:10checkoutTask 11 checked out 已簽出:Fat>>id:11checkoutTask 12 checked out 已簽出:Fat>>id:12checkoutTask 13 checked out 已簽出:Fat>>id:13checkoutTask 14 checked out 已簽出:Fat>>id:14checkoutTask 15 checked out 已簽出:Fat>>id:15checkoutTask 16 checked out 已簽出:Fat>>id:16checkoutTask 18 checked out 已簽出:Fat>>id:18checkoutTask 17 checked out 已簽出:Fat>>id:17checkoutTask 19 checked out 已簽出:Fat>>id:19checkoutTask 20 checked out 已簽出:Fat>>id:20checkoutTask 21 checked out 已簽出:Fat>>id:21checkoutTask 22 checked out 已簽出:Fat>>id:22checkoutTask 23 checked out 已簽出:Fat>>id:23all checkoutTasks created0   >>main() thrad checked out 簽出operation>>  Fat>>id:24checked in 釋放:Fat>>id:1checkoutTask 24 checked out 已簽出:Fat>>id:1checked in 釋放:Fat>>id:21   >>main() thrad checked out 簽出operation>>  Fat>>id:2checked in 釋放:Fat>>id:02   >>main() thrad checked out 簽出operation>>  Fat>>id:0checked in 釋放:Fat>>id:33   >>main() thrad checked out 簽出operation>>  Fat>>id:3checked in 釋放:Fat>>id:44   >>main() thrad checked out 簽出operation>>  Fat>>id:4checked in 釋放:Fat>>id:55   >>main() thrad checked out 簽出operation>>  Fat>>id:5checked in 釋放:Fat>>id:76   >>main() thrad checked out 簽出operation>>  Fat>>id:7checked in 釋放:Fat>>id:97   >>main() thrad checked out 簽出operation>>  Fat>>id:9checked in 釋放:Fat>>id:118   >>main() thrad checked out 簽出operation>>  Fat>>id:11checked in 釋放:Fat>>id:139   >>main() thrad checked out 簽出operation>>  Fat>>id:13checked in 釋放:Fat>>id:1510   >>main() thrad checked out 簽出operation>>  Fat>>id:15checked in 釋放:Fat>>id:1711   >>main() thrad checked out 簽出operation>>  Fat>>id:17checked in 釋放:Fat>>id:2112   >>main() thrad checked out 簽出operation>>  Fat>>id:21checked in 釋放:Fat>>id:1913   >>main() thrad checked out 簽出operation>>  Fat>>id:19checked in 釋放:Fat>>id:2314   >>main() thrad checked out 簽出operation>>  Fat>>id:23checked in 釋放:Fat>>id:8checked in 釋放:Fat>>id:615   >>main() thrad checked out 簽出operation>>  Fat>>id:616   >>main() thrad checked out 簽出operation>>  Fat>>id:8checked in 釋放:Fat>>id:1017   >>main() thrad checked out 簽出checked in 釋放:Fat>>id:14checked in 釋放:Fat>>id:16checked in 釋放:Fat>>id:18checked in 釋放:Fat>>id:20checked in 釋放:Fat>>id:22checked in 釋放:Fat>>id:12operation>>  Fat>>id:1018   >>main() thrad checked out 簽出operation>>  Fat>>id:1219   >>main() thrad checked out 簽出operation>>  Fat>>id:1420   >>main() thrad checked out 簽出operation>>  Fat>>id:1621   >>main() thrad checked out 簽出operation>>  Fat>>id:1822   >>main() thrad checked out 簽出operation>>  Fat>>id:2023   >>main() thrad checked out 簽出operation>>  Fat>>id:22checked in 釋放:Fat>>id:124   >>main() thrad checked out 簽出operation>>  Fat>>id:1任務是否完成:falsecheckOut() interrupted*/





java Semaphore訊號亮-允許多個任務同時訪問這個資源--thinking in java21.7.6

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.