写一个生产者,一个消费者,一个同步队列。
生产者不停的向同步队列写整数,消费者取整数并打印。示例如下:import java.*;
import java.util.*;
import java.lang.*;
import java.io.*;public class test {
  public test() {  }  void go() {
    SynQueue queue = new SynQueue();
    Thread tp = new Thread(new Producer(queue));
    Thread tc = new Thread(new Consumer(queue,System.out));
    tp.start();
    tc.start();
  }  public static void main(String[] args) {
    test t = new test();
    t.go();
  }
}class SynQueue {
  private LinkedList list = new LinkedList();  synchronized void add(int a) {
    java.lang.Integer i = new Integer(a);
    list.addLast(i);
  }  synchronized int pop() {
    if (list.isEmpty()) {
      return 0;
    }
    Integer i = (Integer) list.getFirst();
    list.removeFirst();
    return i.intValue();
  }  synchronized boolean isEmpty() {
    return list.isEmpty();
  }
}class Producer
    implements Runnable {
  private SynQueue queue;
  java.util.Random rdm = new Random();  Producer(SynQueue queue) {
    this.queue = queue;
  }  public void run() {
    while (true) {
      int a = rdm.nextInt() % 100;
      queue.add(a);
      if (a == 0) {
        return;
      }
      
      try {
        Thread.sleep(10);
      }catch (Exception e) {}
    }
  }
}class Consumer implements Runnable {
  private SynQueue queue;
  OutputStream os;
  
  Consumer(SynQueue queue,OutputStream os) {
    this.queue = queue;
    this.os = os;
  }
  
  public void run() {
    java.io.OutputStreamWriter bos = new OutputStreamWriter(os);
    while(true) {
      while(!queue.isEmpty()) {
        int a = queue.pop();
        try {
          bos.write("" + a + "\n");      
          if (a == 0) {
            bos.write("exit.");
            bos.flush();
            return;
          }
        }
        catch (Exception ex) {
          System.out.println(ex.getMessage());
        }        
      }
      try {
        bos.flush();
        Thread.sleep(100);
      }catch (Exception e) {}
    }
  }
}

解决方案 »

  1.   

    up
    但楼上的程序有一处需稍作修改:
    要求的是0到1000之间的随机数,所以要把int a = rdm.nextInt() % 100;
    改为:
    int a = (Math.abs(rdm.nextInt())) % 1000;
      

  2.   

    up
    但楼上的程序有一处需稍作修改:
    要求的是0到1000之间的随机数,所以要把int a = rdm.nextInt() % 100;
    改为:
    int a = (Math.abs(rdm.nextInt())) % 1000;
      

  3.   

    up
    但楼上的程序有一处需稍作修改:
    要求的是0到1000之间的随机数,所以要把int a = rdm.nextInt(1000);
    hehe;
      

  4.   

    是不是搞错了,说的不是JMS吗?