信號(hào)量(Semaphore),實(shí)現(xiàn)方法的并發(fā)限量使用

字號(hào):

package concurrent;
    import java.util.concurrent.Semaphore;
    /**
    * 信號(hào)量,實(shí)現(xiàn)方法的多線程限量使用。
    */
    public class SemaphoreTest extends Thread {
    public static void main(String[] args) {
    for (int i = 0; i <= 10; i++) {
    new SemaphoreTest().start();
    }
    }
    public void run() {
    int i = 2;
    OnlyTwo ot = new OnlyTwo();
    while (i-- > 0) {
    System.out.printf("[%3d]%d=%d\n",this.getId(),System.currentTimeMillis(),+ot.getSomthing());
    try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    ot.returnSomthing();
    }
    }
    }
    class OnlyTwo {
    private static final int MAX_AVAILABLE = 3;
    private static final Semaphore available = new Semaphore(MAX_AVAILABLE, false);
    private static int NUM = 1;
    /**
    * 執(zhí)行方法。
    *
    * @return
    */
    public int getSomthing() {
    try {
    available.acquire();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return NUM++;
    }
    /**
    * 歸還
    */
    public void returnSomthing() {
    available.release();
    }
    }
    運(yùn)行效果
    [ 9]1225837305234=1
    [ 10]1225837305250=3
    [ 8]1225837305250=2
    [ 8]1225837305468=4
    [ 10]1225837305468=6
    [ 9]1225837305468=5
    [ 12]1225837305250=7
    [ 14]1225837305250=8
    [ 16]1225837305250=9
    [ 16]1225837305875=10
    [ 12]1225837305875=12
    [ 14]1225837305875=11
    [ 18]1225837305250=13
    [ 13]1225837305250=15
    [ 11]1225837305250=14
    [ 18]1225837306281=16
    [ 13]1225837306281=18
    [ 11]1225837306281=17
    [ 15]1225837305250=19
    [ 17]1225837305250=20
    [ 17]1225837306687=21
    [ 15]1225837306687=22