JavaSE-多线程(9)- Semaphore

JavaSE-多线程(9)- Semaphore

解释semaphore前先看下以下例子:

例1
有10个线程同时执行SemaphoreTest任务,从执行结果可以看出,10个线程是同时执行的,等待一段时间后结束。

package com.hs.example.base.multithread.day01;

public class SemaphoreTest implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " start ...");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " end ...");
    }

    public static void main(String[] args) {
        SemaphoreTest semaphoreTest = new SemaphoreTest();
        for (int i = 0; i < 10; i++) {
            new Thread(semaphoreTest, "t" + i).start();
        }
    }
}

t2 start ...
t3 start ...
t6 start ...
t7 start ...
t0 start ...
t1 start ...
t4 start ...
t5 start ...
t8 start ...
t9 start ...
t2 end ...
t3 end ...
t0 end ...
t6 end ...
t4 end ...
t7 end ...
t1 end ...
t9 end ...
t5 end ...
t8 end ...

例2

在例2中,同样有10个线程执行同一个任务,但是使用了Semaphore工具类,初始化Semaphore类的入参为2,在run方法开始时调用 semaphore.acquire(); 方法,结束时调用 semaphore.release(); 方法,字面理解为请求和释放,以下程序的意思是当有多个线程执行时,只允许2个线程同时执行,从输出结果交替输出start和end也可看出这一点,而 semaphore.acquire(); 方法的意思是当线程执行到这一步时需要获得semaphore的允许才可继续执行

import java.util.concurrent.Semaphore;

public class SemaphoreTest2 implements Runnable {

    private Semaphore semaphore;

    public SemaphoreTest2(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + " start ...");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        semaphore.release();
        System.out.println(Thread.currentThread().getName() + " end ...");
    }

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        SemaphoreTest2 semaphoreTest = new SemaphoreTest2(semaphore);
        for (int i = 0; i < 10; i++) {
            new Thread(semaphoreTest, "t" + i).start();
        }
    }
}
t0 start ...
t1 start ...
t0 end ...
t3 start ...
t2 start ...
t1 end ...
t3 end ...
t2 end ...
t8 start ...
t5 start ...
t8 end ...
t9 start ...
t6 start ...
t5 end ...
t9 end ...
t4 start ...
t6 end ...
t7 start ...
t4 end ...
t7 end ...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值