Semaphore

作者: 尉昌达 | 来源:发表于2020-07-11 08:58 被阅读0次

示例用法:

public static void main(String[] args) {
        //Semaphore s = new Semaphore(2);
        //Semaphore s = new Semaphore(2, true);
        //允许一个线程同时执行
        Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

相关文章

网友评论

    本文标题:Semaphore

    本文链接:https://www.haomeiwen.com/subject/rrbtcktx.html