`
cjm0000000
  • 浏览: 32168 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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模型好像不支持.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics