最近理解並實作多執行緒程式,這時突然想到3年前ASP.NET筆試題目(參考樂透開球效率問題),想試試看用多執行緒做。

如果想知道ASP.NET-C#怎麼計算Thread總花費時間,詳細參考StackOverFlowCodeProject

單執行緒與多執行緒所花費時間都一樣,差別僅在於使用者等待感覺,多執行緒等待感覺會比單執行緒好。

以下程式能測試執行緒1到N個,至於執行時間會不同是用wait(10);緣故。

 

程式參考資料:

林信良-Openhome Java wait().notify()


結果圖:

ballThread.jpg

 

程式碼:

import java.util.concurrent.ForkJoinWorkerThread;

class WasherTime
{
  private double spendTime = -1;
  public synchronized void setSpend(double spendTime)
  {this.spendTime = spendTime;}
  public synchronized double getSpend()
  {
     while(spendTime ==-1)
     {
        try{
             wait(10);//等待10毫秒
        }catch(InterruptedException ie){
             System.out.println("被中斷了...");
        }
     }
     return spendTime;
  }
}

class Washer implements Runnable
{
   private long wTimeS,wTimeE;
   private int ballStart;
   private int ballEnd;
   private int out_ball;
   private int cha_arr[];
   private int cha_len;
   private int temp;
   private WasherTime washerTime;

   Washer(int ballStart,int ballEnd,WasherTime washerTime)
   {setWasher(ballStart,ballEnd,washerTime);}
   private synchronized void setWasher(int ballStart,int ballEnd,WasherTime washerTime)
   {
     this.ballStart=ballStart;
     this.ballEnd=ballEnd;
     this.washerTime=washerTime;
   }
   //Thread run() Override
   public void run()
   {     
     wTimeS = System.currentTimeMillis();
     //System.out.println("Name:"+Thread.currentThread().getName()+" STime:"+wTimeS/1000.000);
     out_ball = (ballEnd+1)-ballStart;
     cha_len = out_ball;
     cha_arr = new int[cha_len];
     for(int i=0;i<out_ball;i++)
     {cha_arr[i]=i+ballStart;}
     for(int j=0;j<out_ball;j++)
     {       
       temp = (int)(Math.random()*cha_len);
       System.out.print(cha_arr[temp]+" ");
       cha_arr[temp] = cha_arr[cha_len-1];
       cha_len-=1; 
     }      
     wTimeE = System.currentTimeMillis();
     washerTime.setSpend((wTimeE-wTimeS)/1000.000);
     //System.out.println("Name:"+Thread.currentThread().getName()+" Time:"+(wTimeE-wTimeS)/1000.000+"秒");         
   }
}
public class ballThread
{
   public static void main(String args[])
   {                                
      int min_ball = 1;
      int max_ball = 100000;//10萬球
      int washerNum = 10000;//1萬名洗球工具人 1人=9.504秒 100人=11.209秒 10000人=13.508秒
      int start = min_ball;
      int range = ((max_ball+1)-min_ball)/washerNum;
      int end = range;
      double time = 0;
      
      for(int x=0;x<washerNum;x++)
      {         
         WasherTime washerTime = new WasherTime();
         //System.out.println(x+" ballStart:"+start+" ballEnd:"+end);
         Washer washer = new Washer(start,end,washerTime);            
         Thread washerT = new Thread(washer);
         washerT.start();         
         start = end+1;
         end = start+range-1;
         time+=washerTime.getSpend();
      }
      System.out.println("總共花"+time+"秒");                    
   }
}

arrow
arrow
    全站熱搜

    o迷苓o 發表在 痞客邦 留言(0) 人氣()