2012-08-01 26 views
-5

當我運行下面的代碼(這是使用java netbeans編譯器的多線程示例時),我的電腦掛起。
這是爲什麼發生?當使用Java運行多線程代碼時,進程掛起NetBeans編譯器

class clicker implements Runnable 
{ 
    int click=0; 
    Thread t; 
    private volatile boolean runn=true; 
    public clicker(int p) 
    { 
    t=new Thread(this); 
    t.setPriority(p); 
    } 
    public void run() 
    { 
    while(runn) 
     click++; 
    } 
    public void stop() 
    { 
    runn=false; 
    } 
    public void start() 
    { 
    t.start(); 
    } 
} 
public class Hilopri 
{ 
    public static void main(String args[]) 
    { 
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY); 
    clicker hi=new clicker(Thread.NORM_PRIORITY+2); 
    clicker low=new clicker(Thread.NORM_PRIORITY-2); 
    low.start(); 
    hi.start(); 
    try 
    { 
     Thread.sleep(500); 
    } 
    catch(Exception e) 
    { 
     low.stop(); 
     hi.stop(); 
    } 
    try 
    { 
     hi.t.join(); 
     low.t.join(); 
    } 
    catch(Exception e) 
    { 
     System.out.println(e); 
    } 
    System.out.println("Low"+low.click); 
    System.out.println("High"+hi.click); 
    } 
} 
+0

@ user1560596請不要回滾到您的初始後這是不可讀。 – assylias 2012-08-01 11:07:09

+0

@ user1560596很多有意向的人都試圖幫助你解答你的問題。而不是將問題恢復到原來的狀態(許多人會因格式不佳而忽略甚至倒退),請以此爲例來說明如何有效提問:) – Grundlefleck 2012-08-01 11:11:25

+1

是的,我會記住這一點 – user1560596 2012-08-01 11:15:14

回答

2

這是因爲你在catch塊僅如果Thread.sleep(500)拋出< =>中斷異常執行調用low.stop()hi.stop()。並且代碼中沒有任何內容會中斷它。

你可能意味着把停在調用finally塊:

try { 
     Thread.sleep(500); 
    } catch (Exception e) { 
    } finally { 
     low.stop(); 
     hi.stop(); 
    } 
+0

此外,緊密循環可能很容易導致一個內核的CPU使用率達到100%,因此基本上可以停止最多2個內核的機器。 – 2012-08-01 11:02:54

+0

@JensSchauder在代碼中有其他問題要誠實;-) – assylias 2012-08-01 11:06:30

+0

非常感謝它assylias.Cheers兄弟。 – user1560596 2012-08-01 11:09:27

相關問題