-5

当我运行以下代码时,这是使用 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);
  }
}
4

1 回答 1

2

这是因为您在 catch 块中调用low.stop()and ,该块仅在抛出异常 <=> 被中断hi.stop()时才执行。Thread.sleep(500)您的代码中没有任何内容会中断它。

您可能打算将停止调用放在 finally 块中:

    try {
        Thread.sleep(500);
    } catch (Exception e) {
    } finally {
        low.stop();
        hi.stop();
    }
于 2012-08-01T11:00:04.367 回答