编写一个生产者,消费者多线程程序,一个线程随机产生数据,另一个线程显示所产生的数据.

import java.util.*;

public class ThreadSample
{
  private boolean stop_produce = false;
  private boolean stop_consume = false;
  private Vector data;
  private Thread producer;
  private Thread consumer;
  private Random random;
  public ThreadSample()

  {
    data = new Vector();
    random=new Random();
    producer = new Thread()
    {
      public void run()
      {
        try
        {
          while (!stop_produce)
          {

            sleep(1000);
            produceData();
          }

        }

        catch (Exception e)
        {}

      }
    };
    consumer = new Thread()
    {
      public void run()
      {
        try
        {

          while (!stop_consume)
          {
            sleep(1000);
            consumeData();
          }
        }

        catch (Exception e)
        {}
      }
    };

  }

  public void startProduce()
  {
    //if (producer.isInterrupted())
    stop_produce = false;
    producer.start();
  }

  public void stopProduce()
  {
    stop_produce = true;
  }

  public void stopConsume()
  {
    stop_consume = true;
  }

  public void startConsume()
  {
    //if (consumer.isInterrupted())
    stop_consume = false;
    consumer.start();
  }

  private synchronized void produceData()
  {
    Integer i = new Integer(random.nextInt(100));

    data.add(i);

  }

  private synchronized void consumeData()
  {
    if (data.size() != 0)
    {
      //System.out.println(data);
      System.out.println(data.get(random.nextInt(data.size())));
    }
  }

  public static void main(String[] args)
  {
    ThreadSample threadsample = new ThreadSample();
    threadsample.startProduce();
    threadsample.startConsume();
    try
    {
      Thread.sleep(50000);
      threadsample.stopProduce();
      threadsample.stopConsume();
    }
    catch (Exception e)
    {}

  }

}

你可能感兴趣的:(多线程,exception,random,thread,integer,vector)