Java Semaphore Signal Light-consent to multiple tasks visit this resource at the same time--thinking in java21.7.6

Source: Internet
Author: User

Package Org.rui.thread.newc.semaphore;import Java.util.arraylist;import Java.util.list;import java.util.concurrent.semaphore;/** * Agree n Tasks visit this resource at the same time * @author Lenovo * @param <T> */public class Pool<t>{p rivate int size;private list<t> items = new arraylist<t> ();p rivate volatile boolean[] Checkedout;private Sema Phore available;public Pool (class<t> classobject, int size) {this.size = Size;checkedout = new Boolean[size]; Available = new Semaphore (size, true);//Load pool with objects The can is checked out: capable of checking the payload of objects for (int i = 0; i < Size i++) {//assumes a default constructor constructor own Try{//object o=classobject.newinstance ();//fat f= (Fat) Classobject.newinstance (); Items.Add (Classobject.newinstance ());} catch (Exception e) {throw new RuntimeException (e);}}} Assuming you need a new object, you can call CheckOut () and submit it to checkin () public T CheckOut () throws interruptedexception{//after use is complete Assuming there is no semaphore scopes permitted laws card, it means that no object in the pool is available available.acquire ();//Get a license (assuming one is provided) and return immediately, minus 1 of the available licenses. Return GetItems ();} public void CheckIn (T x) {if (Releaseitem (x))//If the object being checked in is valid, a license Available.release () is returned to the signal light, or a license is released to return it to the semaphore. }private synchronized T GetItems () {for (int i = 0; i < size; ++i) {//system.out.println (checkedout[i]); if (!checkedout[i ]//Assume false to indicate that Releaseitem is able to check out {Checkedout[i] = true;//system.out.println ("xxxxxx====" +items.get (i)); return Items.get (i);}} Return null;//semaphore prevents reaching here to prevent the signal from reaching here}private synchronized Boolean releaseitem (T item) {INT index = items . indexOf (item); if (index = =-1) return false;//not in the ListIf (Checkedout[index])//Assuming true indicates that the check-out is able to release {//SYSTEM.OUT.P Rintln ("Releaseitem:" +item); Checkedout[index] = False;return true;} Return false;//wasn ' t checked out not checked out}}

Package Org.rui.thread.newc.semaphore;public class fat{private volatile double d;private static int counter = 0;private fi  nal int id = counter++;p ublic 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++;p rivate int index;private pool<t> pool;public Checko Uttask (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 checked out: "+ Item); TimeUnit.SECONDS.sleep (1); System.out.println ("Checked in Release:" + Item);p Ool.checkin (item);//will run out of the pair like release//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 ();//start Drills poolfor (int i = 0; i < Size; i++) {Exec.execute (new Check Outtask<fat> (pool, i));} System.out.println ("All checkouttasks created");//main starts to check out the Fat objects in the pool-1, but does not check them in.

Once all the objects in the pool are checked out, semaphore will not be running regardless of the checkout operation,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 check out"); F.operation (); List.add (f);} catch (Interruptedexception e) {e.printstacktrace ();}} No object can check out run will clog future<?

> blocked = Exec.submit (new Runnable () {@Overridepublic void run () {try{//semaphore prevents additional checkout semaphore prevention amount Outside of the checksum/So calls is blocked therefore called is blocked pool.checkout ();} catch (Interruptedexception e) {System.err.print ("checkOut () interrupted");//E.printstacktrace ();}}); /hold them for a period of time before signing them into TimeUnit.SECONDS.sleep (2);//To break away from the future. Cancel, the redundant check-in will be ignored by the pool System.out.println ("The task is complete:" +blocked.isdone ()); Blocked.cancel (true);//Break out of the blocked call Interrupt call interruption attempts to cancel the operation of this task System.out.println ();/////////////////is checked in and can continue to use Poolfor (Fat f:list) {Pool.checkin (f);} It is actually possible to use the pool again, for (Fat f:list) {Pool.checkin (f);//second checkIn ignored two to ignore}//exec.shutdown ();}} /** * Output: * Checkouttask 0 checked out checked out: Fat>>id:0checkouttask 2 checked out checked out: Fat>>id:2checkouttask 1 Checked out checked out: Fat>>id:1checkouttask 4 checked out checked out: Fat>>id:3checkouttask 3 checked out checked out: fat>>i D:4checkouttask 5 Checked out checked out: Fat>>id:5checkouttask 6 checked out checked out: Fat>>id:6cheCkouttask 7 checked out checked out: Fat>>id:7checkouttask 8 checked out checked out: Fat>>id:8checkouttask 9 checked out checked out: Fa T>>id:9checkouttask checked out checked out: Fat>>id:10checkouttask One checked out checked out: Fat>>id : 11checkoutTask checked out checked out: Fat>>id:12checkouttask checked out checked out: Fat>>id:13checkouttask 14 Checked out checked out: Fat>>id:14checkouttask checked out checked out: Fat>>id:15checkouttask checked out checked out: fat>& Gt;id:16checkouttask checked out checked out: fat>>id:18checkouttask-checked out checked out: Fat>>id:17checkouttask 19 Checked out checked out: Fat>>id:19checkouttask checked out checked out: Fat>>id:20checkouttask checked out checked out: fat>& Gt;id:21checkouttask checked out checked out: Fat>>id:22checkouttask checked out checked out: Fat>>id:23all Checkouttasks created0 >>main () Thrad checked out checkout operation>> fat>>id:24checked in release: Fat>>id : 1checkoutTask checked out checked out: fat>>id:1checked in Release: fat&Gt;>id:21 >>main () Thrad checked out checkout operation>> fat>>id:2checked in release: Fat>>id:02 >& Gt;main () Thrad checked out checkout operation>> fat>>id:0checked in Release: Fat>>id:33 >>main () Thrad Chec ked out Checkout operation>> fat>>id:3checked in Release: fat>>id:44 >>main () Thrad checked out checkout operation& Gt;> fat>>id:4checked in Release: Fat>>id:55 >>main () Thrad checked out checkout operation>> Fat>> id:5checked in Release: fat>>id:76 >>main () Thrad checked out checkout operation>> fat>>id:7checked in release: Fa t>>id:97 >>main () Thrad checked out checkout operation>> fat>>id:9checked in release: fat>>id:118 &G T;>main () Thrad checked out checkout operation>> fat>>id:11checked in Release: fat>>id:139 >>main () Thrad Checked out checkout operation>> fat>>id:13checked in Release: fat>>id:1510 >>main () Thrad checked out checkout op Eration>> fat>>id:15checked in Release: fat>>id:1711 >>main () Thrad checked out checkout operation>> fat>>id:17checked In Release: fat>>id:2112 >>main () Thrad checked out checkout operation>> fat>>id:21checked in release: Fat>&gt ; id:1913 >>main () Thrad checked out checkout operation>> fat>>id:19checked in release: fat>>id:2314 &GT;&G T;main () Thrad checked out checkout operation>> fat>>id:23checked in Release: fat>>id:8checked in Release: Fat>>id : 615 >>main () Thrad checked out checkout operation>> fat>>id:616 >>main () Thrad checked out checkout Operat Ion>> fat>>id:8checked in Release: fat>>id:1017 >>main () Thrad checked out checkout checked in release: Fat>&gt ; id:14checked in Release: fat>>id:16checked in Release: fat>>id:18checked in Release: fat>>id:20checked in Release:fat> >id:22checked in Release:fat>>id:12operation>> fat>>id:1018 >>main () Thrad checked out checkout Operati On>> fat>>id:1219>>main () Thrad checked out checkout operation>> fat>>id:1420 >>main () Thrad checked out checkout Operation&gt ;> fat>>id:1621 >>main () Thrad checked out checkout operation>> fat>>id:1822 >>main () Thra D checked out checkout operation>> fat>>id:2023 >>main () Thrad checked out checkout operation>> fat>>i d:22checked in Release: fat>>id:124 >>main () Thrad checked out check out operation>> fat>>id:1 task completed: Falsech Eckout () interrupted*/





Java Semaphore Signal Light-consent to multiple tasks visit this resource at the same time--thinking in java21.7.6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.