线程同步与线程调度初探_发牌功能

问题:一个发牌线程和四个取牌线程间的两种同步问题

首先确定一个缓存区,去放一张牌,并设置一个信号量

class CardBuffer {
	private int value;
	private boolean isEmpty=true;
	private int order=0;
	private int number;
	
	CardBuffer(int number){ this.number=number;}
	synchronized void put(int i){
		while(!this.isEmpty)
			try{ this.wait();}
			catch(InterruptedException ex){}
		
			this.value=i;
			this.isEmpty=false;
			this.notifyAll();
	}
	synchronized int get(int order){ //同步锁
		while(this.isEmpty||(this.order!=order))
			try{this.wait();}
			catch(InterruptedException ex){}
		this.isEmpty=true;
		this.notifyAll();
		this.order=(this.order+1)%this.number;
		return this.value;
	}
		
}
然后确定一个发牌线程,每一发出一张牌


class SendCardThread extends Thread{
	private CardBuffer cardbuffer;
	private int cardMax;
	private int number;
	
	public SendCardThread(CardBuffer cardbuffer,int cardMax,int number){
		this.cardbuffer=cardbuffer;
		this.cardMax=cardMax;
		this.number=number;
		this.setPriority(Thread.MAX_PRIORITY);
	}
	public void run(){
		for(int i=1;i<this.cardMax;i++){
			this.cardbuffer.put(i);
		}
		for(int i=1;i<this.number;i++)
			this.cardbuffer.put(-1);
	}
}

确定取牌线程,要考虑到多种情况

class ReceiveCardJFrame extends JFrame implements Runnable{
	private CardBuffer cardbuffer;
	private JTextArea text;
	private int order;
	
	public ReceiveCardJFrame(CardBuffer cardbuffer,int order,String title,int x,int y){
		super(title);
		this.setBounds(x, y, 250, 100);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.order=order;
		this.cardbuffer=cardbuffer;
		this.text=new JTextArea();
		this.getContentPane().add(this.text);
		this.text.setLineWrap(true);
		this.text.setEditable(false);
		this.text.setFont(new Font("Arial",Font.PLAIN,20));
		this.setVisible(true);
		new Thread(this).start();
		
	}
	public void run(){
		while(true){
			int value=this.cardbuffer.get(this.order);
			if(value==-1)
				return;
			this.text.append(String.format("%4d",value));
			try{Thread.sleep(1000);}
			catch(InterruptedException ex){}
		}
	}
}

程序结果如图



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值