import java.awt.*;
import java.awt.event.*;
public class Card extends WindowAdapter
{ Frame f;
TextArea ta1,ta2,ta3,ta4;
public void display()
{ f = new Frame("Send Card");
f.setSize(400,300);
f.setLocation(200,140);
f.setBackground(Color.lightGray);
f.setLayout(new GridLayout(2,2));
f.addWindowListener(this);
ta1 = new TextArea("",5,10,3); //文本区没有滚动条
ta2 = new TextArea("",5,10,3);
ta3 = new TextArea("",5,10,3);
ta4 = new TextArea("",5,10,3);
Font font1 = new Font("Helvetica",Font.PLAIN,20);
ta1.setFont(font1);
ta2.setFont(font1);
ta3.setFont(font1);
ta4.setFont(font1);
f.add(ta1);
f.add(ta2);
f.add(ta4);
f.add(ta3);
f.setVisible(true);
}
public void windowClosing(WindowEvent e)
{ System.exit(0);
}
public static void main(String arg[])
{ Card p = new Card();
p.display();
Buffer3 bf = new Buffer3();
Sender3 s = new Sender3(bf,52);
s.start(); //启动发牌线程
s.setPriority(1); //设置最高优先级,值为1
Receiver3 r1=new Receiver3(bf,p.ta1); //创建四个取牌线程
Receiver3 r2=new Receiver3(bf,p.ta2);
Receiver3 r3=new Receiver3(bf,p.ta3);
Receiver3 r4=new Receiver3(bf,p.ta4);
r1.start(); //启动取牌线程,优先级为5
r2.start();
r3.start();
r4.start();
}
}
class Buffer3 //加互斥锁的缓冲区
{ private int value;
private boolean isEmpty = true; //value是否为空的信号量
private int sort=0; //设定当前取牌线程的顺序值,从0-3
synchronized void put(int i)
{ while (!isEmpty) //当value不空时,等待
{ try
{ wait(); //等待
}
catch(InterruptedException e)
{ System.out.println(e.getMessage());
}
}
value = i; //当value空时,value获得值
isEmpty = false; //设置value为不空状态
notifyAll(); //唤醒所有其他等待线程
}
synchronized int get(String name) //name是当前准备取牌的ta组件名
{ int ptr;
//System.out.println(name); //组件名为:text0-text3
ptr=Integer.parseInt(name.substring(4));//获取组件ta的编号0-3
while (isEmpty||(ptr!=sort))
{ //当value空或组件编号与顺序值不符时,等待
try
{ wait();
}
catch(InterruptedException e)
{ System.out.println(e.getMessage());
}
}
isEmpty = true; //设置value为空状态,并返回值
notifyAll();
sort=(sort+1)%4; //顺序值加1
return value;
}
}
class Sender3 extends Thread //发牌线程
{ private Buffer3 bf;
int count;
public Sender3(Buffer3 bf,int c)
{ this.bf = bf;
this.count = c;
}
public void run( )
{ for (int i=1;i<=count;i++)
bf.put( i );
}
}
class Receiver3 extends Thread //取牌线程
{ private Buffer3 bf;
TextArea ta;
public Receiver3(Buffer3 bf,TextArea ta)
{ this.bf = bf ;
this.ta = ta ;
}
synchronized public void run()
{ while(true)
{ ta.append(" " +bf.get(ta.getName()));
try
{ wait(1000);
}
catch(InterruptedException e)
{ System.out.println(e.getMessage());
}
}
}
}