要求用多线程编写一个打田鼠的游戏,要求程序输出结果为:
跳出第1只田鼠
打第1只田鼠
跳出第2只田鼠
打第2只田鼠
.一直到第100只

解决方案 »

  1.   

    类似生产者-消费者问题:
      可以用两个线程来做,一个线程负责进入队列,一个线程出队列,以前的代码.希望有些参考价值,而不是误导.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();
    }}