2012-08-01 25 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

相关问题