Java 信号量(Semaphore)学习

信号量(Semaphore)为程序并发运行提供了多个通道,在此标记一下。

 

package multithread.semaphore;

import java.security.SecureRandom;
import java.util.concurrent.Semaphore;

/**
 * 模拟超市收银
 * 
 * @author lemzhang
 * 
 */
public class CasherTest {
	private final Semaphore available;

	private final String[] customers;
	
	private final SecureRandom rnd = new SecureRandom();

	public CasherTest(Semaphore available,String[] customers) {
		this.available = available;
		this.customers = customers;
	}

	public void begin() {
		for (String customer : customers) {
			new Thread(new Casher(available, customer), customer).start();
		}
	}

	class Casher implements Runnable {
		private final Semaphore sp;
		private final String customer;

		public Casher(Semaphore sp, String customer) {
			this.sp = sp;
			this.customer = customer;
		}

		@Override
		public void run() {
			try {
				sp.acquire();
				Thread.sleep(generateWorkTimeMillis());
				System.out.printf("[%s]开始结账,%s\n", customer,sp);
				Thread.sleep(generateWorkTimeMillis());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				sp.release();
				System.out.printf("[%s]结账完毕.\n", customer);
			}
		}
	}
	
	private int generateWorkTimeMillis(){
		return rnd.nextInt(5000);
	}
	
	public static void main(String[] args){
		//模拟20个顾客排队结账
		final String[] customers = new String[20];
		for (int i = 0; i < 20; i++) {
			customers[i] = "消费者" + i;
		}
		//模拟5条收银通道
		final Semaphore available = new Semaphore(5);
		
		CasherTest t = new CasherTest(available,customers);
		t.begin();
	}
}

 

如果想要知道某个消费者走的是哪一条收银通道,Semaphore模型好像不支持.

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值