问题:一个发牌线程和四个取牌线程间的两种同步问题
首先确定一个缓存区,去放一张牌,并设置一个信号量
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){}
}
}
}
程序结果如图