当前位置: 代码迷 >> J2SE >> 大家都过来看看这个有关问题。如何解决
  详细解决方案

大家都过来看看这个有关问题。如何解决

热度:109   发布时间:2016-04-24 14:23:04.0
大家都过来看看这个问题。。。怎么解决?
要求用多线程编写一个打田鼠的游戏,要求程序输出结果为:
跳出第1只田鼠
打第1只田鼠
跳出第2只田鼠
打第2只田鼠
.。。。。。。。。。。。。。。。一直到第100只

------解决方案--------------------
怎么让线程不抢占资源呀
--------------------------
什么线程抢占资源??楼主在说什么??
------解决方案--------------------
类似生产者-消费者问题:
可以用两个线程来做,一个线程负责进入队列,一个线程出队列,以前的代码.希望有些参考价值,而不是误导.

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();
}

}
  相关解决方案