Semaphore

核能气质少年 提交于 2019-12-19 01:45:17
package com.company.bingfa;

import java.util.concurrent.Semaphore;

class WC extends Thread{

    private Semaphore sem;

    WC(Semaphore sem){
        this.sem = sem;
    }

    @Override
    public void run() {
        if (sem.availablePermits()>0)
            System.out.println(getName()+"发现有空位");
        else
            System.out.println(getName()+"没有位子,等待中..");
        try {
            sem.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(getName()+"开始使用...");

        try {
            sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(getName()+"使用完毕---");

        sem.release();
    }
}

public class MySemaphore {
    public static void main(String[] args) throws InterruptedException {
        Semaphore sem = new Semaphore(3);

        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new WC(sem);
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }

        System.out.println("主线程结束");
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!