}
package cn.hncu.cardThread;
import java.nio.Buffer;
public class CardDeal {
private String titles[]={"东","南","西","北"};
private int x[]={400,100,400,700};
private int y[]={200,320,440,320};
public CardDeal(int number){
CardBuffer cardbuffer = new CardBuffer(number);
new SendCardThread(cardbuffer,number).start();
for(int i=0;i
}
}
public static void main(String[] args) {
new CardDeal(4);
}
}
package cn.hncu.cardThread;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.TextArea;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class ReceiveCardJFrame extends JFrame implements Runnable {
private JTextArea text=null;
private CardBuffer cardbuffer=null;
private int order;
public ReceiveCardJFrame(CardBuffer cardbuffer, int order, String titles, int x, int y) {
super(titles);
this.cardbuffer = cardbuffer;
this.order = order;
this.setBounds(x, y, 290, 100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
text=new JTextArea();
text.setLineWrap(true);
text.setFont(new Font("a", Font.HANGING_BASELINE, 20));//隐藏了,一会再出来
this.getContentPane().add(text);
text.setEditable(false);
this.setVisible(true);
new Thread(this).start();
}
@Override
public void run() {
while (true) {
int value = cardbuffer.getCard(order);
if(value==-1){
break;
}
text.append(String.format("%4d", value));
try {
Thread.sleep(100);//延迟
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package cn.hncu.cardThread;
import java.util.Date;
import java.util.Random;
public class SendCardThread extends Thread {
private CardBuffer cardBuffer;//缓冲区(加互斥锁)
private int number;//人数
public SendCardThread(CardBuffer cardBuffer, int number) {
super();
this.cardBuffer = cardBuffer;
this.number = number;
}
@Override
public void run() {
int cards[]=new int[54];
for (int i = 0; i < cards.length; i++) {
cards[i]=i+1;
}
//洗牌shuffle算法
Random r=new Random(new Date().getTime());
for(int i=0;i
cards[i] = cards[i]^cards[n];
cards[n] = cards[i]^cards[n];
cards[i] = cards[i]^cards[n];
}
for (int i = 0; i < cards.length; i++) {
cardBuffer.putCard(cards[i]);
}
for(int i=0;i
System.out.println("玩家"+(i+1)+"发完牌了");
}
}
}