JAVA线程中的发牌题
2024-08-27 02:52:35
发牌题主要考虑的就是线程的问题,一个buffer缓冲区的问题,
首先,发牌的优先级当然是最高的了,但是取牌不能有优先级,否则会一直有牌先取,因此需要一个信号量order,当order=线程的数字时,取get
否则等待,
因此这个只能是线程的基础题吧,我也是刚刚把例题的基本含义搞懂,写下来记录一下
package fapai; public class CardBuffer<T> {
private T obj;
private boolean isEmpty=true;
private int number;
private int order=0;
public CardBuffer(int number)
{
this.number=number;
}
public synchronized void put(T obj)
{
while(!isEmpty)
{
try
{
this.wait();
}
catch(InterruptedException ex){}
}
this.obj=obj;
this.isEmpty=false;
this.notifyAll();
}
public synchronized T get(int order)
{
while(this.isEmpty||this.order!=order)
{
try
{
this.wait();
}
catch(InterruptedException ex){} }
this.isEmpty=true;
this.order=(this.order+1)%this.number;
this.notifyAll();
return this.obj; }
} package fapai; public class CardSendThread extends Thread{
private CardBuffer<Integer> buffer;
private int cardMax,number;
public CardSendThread(CardBuffer<Integer> buffer,int cardMax,int number)
{
this.buffer=buffer;
this.cardMax=cardMax;
this.number=number;
this.setPriority(Thread.MAX_PRIORITY);
}
public void run()
{
for(int i=1;i<=this.cardMax;i++)
this.buffer.put(i);
for(int i=1;i<=this.number;i++)
this.buffer.put(null);
} } package fapai;
import java.awt.*;
import javax.swing.*;
public class CardReceiveJFrame extends JFrame implements Runnable {
private CardBuffer<Integer> buffer;
private JTextArea text;
private int order;
public CardReceiveJFrame(CardBuffer<Integer>buffer,int order,String title,int x,int y)
{
super(title);
this.setBounds(x,y,290,100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.buffer=buffer;
this.order=order;
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)
{
Integer value=this.buffer.get(this.order);
if(value==null)
return ;
this.text.append(String.format("%4d",value));
try
{
Thread.sleep(100);
}
catch(InterruptedException ex){}
}
} } package fapai; public class Deal {
public Deal(int cardMax,int number)
{
CardBuffer<Integer> buffer=new CardBuffer<Integer>(number);
new CardSendThread(buffer,cardMax,number).start();
String titles[]={"北","东","南","西"};
int x[]={400,700,400,100},y[]={200,320,440,320};
for(int i=0;i<number;i++)
new CardReceiveJFrame(buffer,i,titles[i],x[i],y[i]);
}
public static void main(String arg[])
{
new Deal(52,4);
} }
最新文章
- IBatisNet -- 保护你的配置文件及映射文件信息
- Swift—调用系统相册和相机
- [Angularjs]asp.net mvc+angularjs+web api单页应用
- [Effective JavaScript 笔记] 第8条:尽量少用全局对象
- Windows 7下配置JDK环境变量
- MySQL表损坏预防与修复
- Linux下安装yum工具
- Android 代码混淆
- 访问nginx-php页面的时候 报access denied.
- mysql4 - 高级操作
- angularjs promise详解
- ROS系统MoveIt玩转双臂机器人系列(一)
- HTML5的优点与缺点?
- Java工程师学习指南 中级篇
- xubuntu无法进图形界面问题
- mac-内置截图-snapshot
- OpenCV 学习笔记 02 使用opencv处理图像
- [原]openstack-kilo--issue(一) httpd汇总
- 匹配img标签的正则表达式
- 3.PO如何给开发团队讲好故事