Mackou991 发表于 2008-9-1 11:42

请教一个多线程问题

这面是一个多线程的程序,请问是怎样来回调用的,也就是怎样执行的-----执行顺序?哪位朋友知道的话,请指点一下,我在这里先谢了!
import java.io.*;
import java.lang.*;
public class synchoronizedThread
{
   public static void main(String args[])
   {
        /**构建Dealer对象*/
        Dealer dealer=new Dealer();
        /**构建和启动生产者和消费者线程*/
       new testThread(dealer,"Consumer").start();
       new testThread(dealer,"Producer").start();
   }


}


class Dealer
{
    int goods=0;
    public synchronized int consume()
    {
       int temp;
       while(goods==0);
      {
          try
          {
               /**使线程进入等待状态*/
               wait();
          }
          catch(InterruptedExcepion e){}
      }
      temp=goods;
      System.out.println("Consumed: "+temp);
      goods--;
      /**唤醒对该对象的等待进程*/
      notify();
      return temp;
   }

   public synchronized void produce(int amout)
   {
      while(goods!=0)
      {
        try
           {
            /**使线程进入等待状态*/
            wait();
           }
        catch(InterruptedException e)
         {
         }
      }
      goods=amout;
      /**唤醒对该对象的等待进程*/
     notyfy();
     System.out.println("produced: "+goods);
   }



}


class testThread extends Thread
{
  booean producer;
  Dealer dealer;

  public testThread(Dealer d,String type)
  {
      dealer =d;
      if(type.equals("Producer"))
           producer=true;
      if(type.equals("Consumer"))
           producer=false;
  }


  public  void run()
  {
     for(int i=0;i<10;i++)
     {
        try
        {
           sleep((int)(Math.random()*200));
        }
        catch(InterruptedException e)
        {
        }
        if(producer)
            dealer.produce((int)(Math.random()*10)+1);
        else
            dealer.consume();
     }
   }

林中剑影 发表于 2008-9-1 13:37

执行顺序?!线程本来就不容易确定顺序,!同一个程序每次运行的结果可能会不同,不同的机运行的结果也会不同!

w362034710 发表于 2008-9-4 16:51

大概就是二个线程类走走停停,似乎synchronized 不需要在你的这个程序里面。

页: [1]

编程论坛