Semaphore

                                    Semaphore
package com.qqjx.thread;
import java.util.concurrent.Semaphore;

public class T11_TestSemaphore {

    public static void main(String[] args) {
        //Semaphore s = new Semaphore(2);
                        //2个信号量 最多运行多少个线程同时运行
                        //若将第一个参数改为1可以打印控制台测试
        Semaphore s = new Semaphore(2, true);
        //允许一个线程同时执行
        //Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();//将信号量-1

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

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();//将信号量+1
            }
        }).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 s = new Semaphore(2, true);
T1 running...
T2 running...
T1 running...
T2 running...
Semaphore s = new Semaphore(1, true);
T1 running...
T1 running...
T2 running...
T2 running...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值