【问题标题】:Process hangs when running multi threading code using Java NetBeans Compiler [closed]使用 Java NetBeans 编译器运行多线程代码时进程挂起 [关闭]
【发布时间】:2012-08-01 10:53:27
【问题描述】:

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

【问题讨论】:

  • @user1560596 请不要回滚到您最初无法阅读的帖子。
  • @user1560596 很多好心的人都试图帮助您获得问题的答案。与其将问题恢复到其原始状态(由于格式不佳,许多人会忽略甚至否决),而是将其作为如何有效提问的示例:)
  • 是的 Grundlefleck 我会记住这一点
  • 停止回滚更改。或者更确切地说,在锁定问题后停止回滚。

标签: java multithreading freeze


【解决方案1】:

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

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

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

【讨论】:

  • 紧循环也很容易导致一个核心的 CPU 使用率达到 100%,因此基本上停止了一台最多有 2 个核心的机器。
  • @JensSchauder 老实说代码中还有其他问题;-)
  • 非常感谢 assylias.Cheers Bro.
  • 非常感谢 Jens 的解释。
猜你喜欢
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多