java5的Semaphore同步工具简单实例

package cn.tool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoneTest {

    /**
     *Semaphone可以维护当前访问自身的线程个数,并提供了同步机制。
     * 使用Semaphone可以控制当前访问资源的线程的个数。例如,实现一个文件的并发访问数。
     */

    /**
     * 创建一个线程池,里面有10个线程。Semaphone中只允许三个线程访问
     * Semaphone 没有互斥锁的作用。
     */
    public static void main(String[] args) {
        // 会根据创建的10个任务来创建10个线程
   ExecutorService pool=Executors.newCachedThreadPool();
    final Semaphore sa=new Semaphore(3);
   for(int i=0;i<10;i++){
       Runnable ren=new Runnable(){

        @Override
        public void run() {
            try {
                sa.acquire();
                for(int i=0;i<4;i++){
                    Thread.sleep(50);
                    System.out.println(Thread.currentThread().getName()+" "+i);
                }   
                sa.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
       };
        pool.execute(ren);

       }
   }



}
运行结果如下:
从结果可以看出,同时有三个线程在并发执行,但这三个线程并没有加互斥锁,所以结果交替输出。
pool-1-thread-1 0
pool-1-thread-2 0
pool-1-thread-6 0
pool-1-thread-1 1
pool-1-thread-2 1
pool-1-thread-6 1
pool-1-thread-1 2
pool-1-thread-2 2
pool-1-thread-6 2
pool-1-thread-1 3
pool-1-thread-2 3
pool-1-thread-6 3
pool-1-thread-3 0
pool-1-thread-5 0
pool-1-thread-4 0
pool-1-thread-3 1
pool-1-thread-5 1
pool-1-thread-4 1
pool-1-thread-3 2
pool-1-thread-5 2
pool-1-thread-4 2
pool-1-thread-3 3
pool-1-thread-5 3
pool-1-thread-4 3
pool-1-thread-7 0
pool-1-thread-9 0
pool-1-thread-8 0
pool-1-thread-7 1
pool-1-thread-9 1
pool-1-thread-8 1
pool-1-thread-7 2
pool-1-thread-9 2
pool-1-thread-8 2
pool-1-thread-7 3
pool-1-thread-9 3
pool-1-thread-8 3
pool-1-thread-10 0
pool-1-thread-10 1
pool-1-thread-10 2
pool-1-thread-10 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值