2011-04-30 69 views
0

我正在編寫一個將運行多線程庫的代碼。我首先用一個程序創建一個線程數組,然後將它們傳遞給另一個運行循環來啓動它們的線程。對於應用程序的一部分,我有一個CPU密集型方法,基本上在一個循環內運行一系列循環。唯一的問題是,由於某種原因,它不會產生我認爲應該的方式。這裏是正在運行的線程的代碼:Java線程產生/飢餓問題

public void run(){ 
    this.setPriority(MAX_PRIORITY); 
    int count = 0; 

    while(count<transactions.length){ 
     int copy = count; 
      if(transactions[copy] instanceof Jumbler){ 
       System.out.println(copy + " is a jumbler."); 
      } 
      else{ 
       System.out.println(copy + " is not a jumbler"); 
      } 
     transactions[copy].run(); 
     count++; 
    } 

    } 

然後這裏是Jumbler run方法:

public void run(){ 
    System.out.println("running jumbler"); 
    Thread.yield(); 
    Thread.currentThread().yield(); 
    try{ 
     Thread.currentThread().sleep(5000); 
    }catch(InterruptedException e){} 
    //this.setPriority(MIN_PRIORITY); 
    System.out.println("still running."); 
    Thread.yield(); 
    nums = new int[1000]; 
    int i = 0; 

    do{ 
     Thread.yield(); 

     for(int x=0;x<1000;x++){ 
      Thread.yield(); 
      //System.out.println("in the loop"); 
      nums[x]=(int)(Math.random()*10000)+1; 
      for(int y = 0;y<1000;y++){ 
       Thread.yield(); 
       //System.out.println("in the the loop"); 
       for(int z = 0;z<100;z++){ 
        Thread.yield(); 
       } 
      } 
     } 
     Thread.yield(); 
     i++; 
     System.out.println(whichJumble + ": " + i); 
    }while(i<1000); 
} 

所以,問題是,我希望它屈服,允許的主要方法繼續運行更多線程,但會阻塞並等待Jumbler完成(這需要很長時間)。任何想法爲什麼會發生或如何解決它?

+0

yield方法不能保證線程實際上會產生CPU,你最好使用1毫秒的休眠,或者創建優先級較低的線程。 – 2011-04-30 19:51:30

回答

-1

一旦線程運行,我不認爲你可以保證當你調用setPriority時優先級改變。

這兩個語句做同樣的事情:

Thread.yield(); 
Thread.currentThread().yield(); 

,但你可能不應該叫屈服,讓操作系統做到這一點。

1

看來你是正確產卵線程(其實,你不產卵他們在所有)

如果你想有一個線程開始運行(同時當前線程),你需要調用該Thread對象的start()方法,您不知道。

如果我正確理解你的代碼,你想要第一個片段產生其他線程。因此,您應該將transactions[copy].run()更改爲transactions[copy].start()

(這有根據的猜測,如果你表現出transaction定義數組這將是很好。)

這裏的下水多個線程的典型方案:

class MyThread extends Thread { 
    public void run() { 
    // Do something here ... 
    } 
} 


// Prepare the array 
MyThread[] arr = new MyThread[10]; 
for(int i = 0; i < arr.length; ++i) 
    arr[i] = new MyThread(); 

... 

// Launch the threads 
for(int i = 0; i < arr.length; ++i) 
    arr[i].start(); 
6

我想這個問題來在您的主循環中使用transactions[copy].run();。這個直接調用run方法,但不能在另一個系統線程中調用。請改用transactions[copy].start();開始線程。