大家都过来看看这个问题。。。怎么解决?

goyangtao 2007-07-23 06:53:37
要求用多线程编写一个打田鼠的游戏,要求程序输出结果为:
跳出第1只田鼠
打第1只田鼠
跳出第2只田鼠
打第2只田鼠
.。。。。。。。。。。。。。。。一直到第100只
...全文
148 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
IhaveGotYou 2007-07-23
  • 打赏
  • 举报
回复
类似生产者-消费者问题:
可以用两个线程来做,一个线程负责进入队列,一个线程出队列,以前的代码.希望有些参考价值,而不是误导.

package net.oicp.sunflowerbbs;

import java.util.Random;

enum Operate {
push, pop
};

class Queue {
private int MaxSize = 10;

private int[] array;

private int top = -1;

Queue() {
this(10);
};

Queue(int size) {
this.MaxSize = size;
assert (size >= 0);
array = new int[size];
}

public synchronized void operate(Operate theOperate,int x)
{
switch(theOperate){
case push:
try
{
while(top >= MaxSize)
wait();
top++;
array[top] = x;
notifyAll();
System.out.println("进:"+x);
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case pop:
try
{
while((top <= -1))
wait();
System.out.println("出:"+array[top--]);
notifyAll();
}
catch(Exception e)
{
e.printStackTrace();
}
break;
default:

}
}


}

class MyThread extends Thread
{
private static Queue q=new Queue(20);
private Random rd=new Random();
Operate op;
public void run()
{
String threadName = Thread.currentThread().getName();
try
{
while(!interrupted())
{
if(threadName.equals("A"))
{
q.operate(op.push,rd.nextInt(100));
}
if(threadName.equals("B"))
{
q.operate(op.pop, 10);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}

}
}


public class ThreadCP {
public static void main(String[] args) {
Thread t1=new Thread(new MyThread(),"A");
//t1.setPriority(5);
Thread t2=new Thread(new MyThread(),"B");
//t2.setPriority(1);
t1.start();
t2.start();
}

}
goyangtao 2007-07-23
  • 打赏
  • 举报
回复
只要用多资源做出来这个题,就可以了
熊孩子开学喽 2007-07-23
  • 打赏
  • 举报
回复
怎么让线程不抢占资源呀
--------------------------
什么线程抢占资源??楼主在说什么??
goyangtao 2007-07-23
  • 打赏
  • 举报
回复
怎么让线程不抢占资源呀。。。谢谢

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧