我正在編寫一個將運行多線程庫的代碼。我首先用一個程序創建一個線程數組,然後將它們傳遞給另一個運行循環來啓動它們的線程。對於應用程序的一部分,我有一個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完成(這需要很長時間)。任何想法爲什麼會發生或如何解決它?
yield方法不能保證線程實際上會產生CPU,你最好使用1毫秒的休眠,或者創建優先級較低的線程。 – 2011-04-30 19:51:30