当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

Semaphore 使用案例

发表于: 2014-04-10   作者:abc08010051   来源:转载   浏览:
摘要:    Semaphore即信号量,可以被多个线程获取,下面是一个具体的例子,和Lock配合使用,模拟有三台打印机,一次允许三个线程使用空闲的打印机,代码如下: package thread; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import ja

   Semaphore即信号量,可以被多个线程获取,下面是一个具体的例子,和Lock配合使用,模拟有三台打印机,一次允许三个线程使用空闲的打印机,代码如下:

package thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * User: malone
 * Date: 14-4-10
 * Time: 上午10:39
 * To change this template use File | Settings | File Templates.
 */
public class SemaphoreDemo {

    public static void main (String[] args) {
        Storge storge = new Storge();
        for (int i = 0; i < 12; i++) {
            new MyThread(storge).start();
        }
    }
}

class Storge {

    private volatile Boolean[] printer;

    private Semaphore semaphore;

    private Lock lock;

    Storge () {
        semaphore = new Semaphore(3);
        printer = new Boolean[3];
        for (int i = 0; i < printer.length; i++) {
            printer[i] = true;
        }
        lock = new ReentrantLock();
    }

    public int getFreePrinter () {
        lock.lock();
        try {
            for (int i = 0; i < printer.length; i++) {
                if (printer[i]) {
                    printer[i] = false;
                    return i;
                }
            }
        } finally {
            lock.unlock();
        }
        return -1;
    }

    public void setPrinter (int i) {
        lock.lock();
        try {
            printer[i] = true;
        } finally {
            lock.unlock();
        }
    }

    public void print () {
        try {
            //获取信号量
            semaphore.acquire();
            int freePrinter = getFreePrinter();
            System.out.println("Thread " + Thread.currentThread().getName() + " 正在使用"  + freePrinter + "号打印机");
            Thread.sleep(1000);
            setPrinter(freePrinter);
            System.out.println("Thread " + Thread.currentThread().getName() + " 释放"  + freePrinter + "号打印机");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }

    }


}

class MyThread extends Thread {
    private Storge storge;

    MyThread (Storge storge) {
        this.storge = storge;
    }

    public void run () {
        storge.print();
    }

}


 

Semaphore 使用案例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号