semaphore n个资源分配给m个线程的案例

Winson
  • 6

就是n个线程,线程要使用某个具体的对象,比如显示器monitor,
一共有m个monitor。
遇到的问题主要有:首先semaphore的acquire只是获取许可,没有拿到对象,没有拿到空闲对象。
求大神写一个案例。

回复
阅读 1k
1 个回答
@Data
class SemaphoreWithResource {
    Semaphore semaphore = new Semaphore(5);
    CopyOnWriteArrayList<Resource> resources = new CopyOnWriteArrayList<>();


    public SemaphoreWithResource() {
        //构建5个资源类
        for (int i = 0; i < 5; i++) {
            resources.add(new Resource(i, String.valueOf(i)));
        }
    }

    //能够同时获得许可和资源
    public  void acquire(WorkerThread workerThread) {
        Resource poll = null;
        try {
            semaphore.acquire();
            poll = resources.remove(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerThread.setResource(poll);
        }
    }

    //能够同时释放许可和资源
    public   void release(WorkerThread workerThread) {
        try {
            semaphore.release();
            resources.add(workerThread.getResource());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerThread.setResource(null);
        }
    }
}


public class SemaphoreDemo {
    public static void main(String[] args) {
        int ThreadCount = 8;
        SemaphoreWithResource semaphoreWithResource = new SemaphoreWithResource();
        //创建8个线程来操作5个资源类
        for (int i = 0; i < ThreadCount; i++) {
            WorkerThread workerThread = new WorkerThread(semaphoreWithResource);
            workerThread.setName(String.valueOf(i));
            workerThread.start();
        }
        System.out.println("main has been dead");
    }

}

@Data
class Resource {
    private int number;
    private String name;

    public Resource() {

        number = 0;
    }

    public Resource(int number) {
        this.number = number;
    }

    public Resource(int number, String name) {
        this.number = number;
        this.name = name;
    }
}


@Data
class WorkerThread extends Thread {
    private Resource resource;
    private SemaphoreWithResource semaphore;

    public WorkerThread(SemaphoreWithResource semaphore) {
        resource = null;
        this.semaphore = semaphore;

    }

    @Override
    public void run() {
        acquire();
        int number = resource.getNumber();
        int randomInt = new Random(Instant.now().toEpochMilli()).nextInt(10);
        resource.setNumber(number + randomInt);
        System.out.println("第" + getName() + "线程把资源类" + resource.getName() + "的值从"
                + number + "改为了" + resource.getNumber());
        release();
    }
    private void acquire() {
        if (resource == null) {
            semaphore.acquire(this);
        }
    }
    private void release() {
        semaphore.release(this);
    }
}
宣传栏