有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不能调用包含线程的方法。睡眠方法

我正在实现线程。sleep()在一个方法中,我试图从另一个类调用这个方法;然而,每次我这么做,代码都会冻结。我有一种感觉,它与该线程的中断异常有关。睡眠导致

以下是一个示例:

类名是一个

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

单独上课

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

start()在一个类中,call()在另一个类中,call()试图从第一个类调用start方法


共 (3) 个答案

  1. # 1 楼答案

    使用这种条件使while循环永不停止不是明智之举, 这是一个死循环,所以它会冻结

    while (true) {  
            Thread.sleep(10);
        }
    
  2. # 2 楼答案

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

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

     every time I do this the screen just freezes
    

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