-5

Java NetBeansコンパイラを使用したマルチスレッドの例である以下のコードを実行すると、PCがハングします。
なぜこれが起こるのですか?

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()、 <=>が中断されたためです。そして、あなたのコードの何もそれを中断しません。hi.stop()Thread.sleep(500)

あなたはおそらくストップコールをfinallyブロックに入れるつもりでした:

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