展开全部
// 发牌程序。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardBuffer //加互斥锁的缓冲区
{
private int value;
private boolean isEmpty = true; //value是否为空的信号量
private int order=0; //信号量,e68a8462616964757a686964616f31333236373165约定取牌线程的次序
synchronized void put(int i)
{
while (!isEmpty) //当value不空时,等待
{
try
{
this.wait(); //等待
}
catch(InterruptedException e) {}
}
value = i; //当value空时,value获得值
isEmpty = false; //设置value为不空状态
notifyAll(); //唤醒所有其他等待线程
}
synchronized int get(int order) //order是取牌线程约定的次序
{
while (isEmpty || (this.order!=order)) //当value空或取牌次序不符时等待
{
try
{
this.wait();
}
catch(InterruptedException e) {}
}
isEmpty = true; //设置value为空状态,并返回值
notifyAll();
this.order = (this.order+1)%4; //加1使取牌次序轮转
return value;
}
}
class Sender extends Thread //发牌线程类
{
private CardBuffer cardbuffer;
private int count;
public Sender(CardBuffer cardbuffer,int count)
{
this.cardbuffer = cardbuffer;
this.count = count;
}
public void run()
{
for (int i=1;i<=this.count;i++)
cardbuffer.put(i);
}
}
class Receiver extends Thread //取牌线程类
{
private CardBuffer cardbuffer;
private JTextArea text;
private int order; //信号量,约定取牌线程的次序
public Receiver(CardBuffer cardbuffer,JTextArea text,int order)
{
this.cardbuffer = cardbuffer ;
this.text = text ;
this.order = order;
}
public void run()
{
while(true)
{
text.append(" "+cardbuffer.get(this.order));
try
{
this.sleep(100);
}
catch(InterruptedException e) {}
}
}
}
class CardJFrame extends JFrame
{
public CardJFrame()
{
super("发牌程序");
this.setSize(430,200);
this.setLocation(300,240);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new GridLayout(3,3,5,5)); //3行3列网格布局,间隔为5
JTextArea text_north,text_east,text_south,text_west; //获得牌的4个文本区
text_north = new JTextArea();
text_east = new JTextArea();
text_south = new JTextArea();
text_west = new JTextArea();
text_north.setLineWrap(true); //设置文本区自动换行
text_east.setLineWrap(true);
text_south.setLineWrap(true);
text_west.setLineWrap(true);
text_north.setEditable(false);
text_east.setEditable(false);
text_south.setEditable(false);
text_west.setEditable(false);
Font font = new Font("Helvetica", Font.PLAIN, 16);
text_north.setFont(font);
text_east.setFont(font);
text_south.setFont(font);
text_west.setFont(font);
this.add(new JPanel()); //网格布局的第1行
this.add(text_north);
this.add(new JPanel());
this.add(text_west); //网格布局的第2行
this.add(new JPanel());
this.add(text_east);
this.add(new JPanel()); //网格布局的第3行
this.add(text_south);
this.add(new JPanel());
this.setVisible(true);
CardBuffer cardbuffer = new CardBuffer();
Sender s = new Sender(cardbuffer,52);
s.setPriority(10); //设置最高优先级
s.start(); //启动发牌线程
(new Receiver(cardbuffer,text_north,0)).start(); //创建并启动4个取牌线程,优先级为5
(new Receiver(cardbuffer,text_east,1)).start();
(new Receiver(cardbuffer,text_south,2)).start();
(new Receiver(cardbuffer,text_west,3)).start();
}
public static void main(String arg[])
{
new CardJFrame();
}
}
本回答由提问者推荐
已赞过
已踩过<
你对这个回答的评价是?
评论
收起