Semaphore拿到执行权的线程之间是否互斥

java线程之间的控制,使用Semaphore 实现 互斥

下面我们通过Semaphore来实现一个比较好的互斥操作:

package com.zhy.concurrency.semaphore;  
  
import java.util.concurrent.Semaphore;  
  
/** 
 * 使用信号量机制,实现互斥访问打印机 
 *  
 *  
 */  
public class MutexPrint  
{  
  
    /** 
     * 定义初始值为1的信号量 
     */  
    private final Semaphore semaphore = new Semaphore(1);  
  
    /** 
     * 模拟打印操作 
     * @param str 
     * @throws InterruptedException 
     */  
    public void print(String str) throws InterruptedException  
    {  
        //请求许可  
        semaphore.acquire();  
          
        System.out.println(Thread.currentThread().getName()+" enter ...");  
        Thread.sleep(1000);  
        System.out.println(Thread.currentThread().getName() + "正在打印 ..." + str);  
        System.out.println(Thread.currentThread().getName()+" out ...");  
        //释放许可  
        semaphore.release();  
    }  
  
    public static void main(String[] args)  
    {  
        final MutexPrint print = new MutexPrint();  
  
        /** 
         * 开启10个线程,抢占打印机 
         */  
        for (int i = 0; i < 10; i++)  
        {  
            new Thread()  
            {  
                public void run()  
                {  
                    try  
                    {  
                        print.print("helloworld");  
                    } catch (InterruptedException e)  
                    {  
                        e.printStackTrace();  
                    }  
                };  
            }.start();  
        }  
  
    }  
  
}

输出结果:

Thread-1 enter ...  
Thread-1正在打印 ...helloworld  
Thread-1 out ...  
Thread-2 enter ...  
Thread-2正在打印 ...helloworld  
Thread-2 out ...  
Thread-0 enter ...  
Thread-0正在打印 ...helloworld  
Thread-0 out ...  
Thread-3 enter ...  
Thread-3正在打印 ...helloworld  
Thread-3 out ...  

 

转载于:https://www.cnblogs.com/liuqing576598117/p/11168846.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值