【问题标题】:Cannot call a method which includes Thread.sleep method无法调用包含 Thread.sleep 方法的方法
【发布时间】:2014-06-17 01:38:00
【问题描述】:

我正在一个方法中实现 Thread.sleep() 并尝试从另一个类调用此方法;但是,每次我这样做时,代码都会冻结。我有一种感觉,它与 Thread.sleep() 导致的 InterruptedException 有关。

这是一个示例:

类名是 A

....
public static void start() throws InterruptedException
{
    //other code
    while (true) {
        Thread.sleep(10);
    }
}
...

单独的类

    ...
    public static void call()
    {
        new A().start();
    }
    ...

start() 在一个类中,call() 在一个单独的类中,call() 正在尝试从第一个类调用 start 方法。

【问题讨论】:

  • 你在while 循环中永远循环,你在问为什么你的代码停在那里?

标签: java multithreading exception-handling


【解决方案1】:
 every time I do this the screen just freezes

那是因为while loop 中的Thread.sleep(10); 会将您当前的线程置于阻塞状态,从而冻结您的屏幕。

【讨论】:

    【解决方案2】:

    一旦你调用了方法,while循环就开始了,它永远不会因为它的条件而停止!

      while (true) {  <<<<<<<<<< change it to a logical condition or take it out
            Thread.sleep(10);
        }
    

    【讨论】:

      【解决方案3】:

      使用这个条件使得这个while循环永远不会停止是不明智的, 这是一个死循环,这就是它冻结的原因。

      while (true) {  
              Thread.sleep(10);
          }
      

      【讨论】:

        猜你喜欢
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        相关资源
        最近更新 更多