-1

我对 Thread.sleep() 的工作原理有点困惑:

  1. 如果我在 main 方法中调用它,并且还有其他创建的线程正在运行。它会暂停什么:单独的主线程或其所有子线程(将它们视为主线程的一部分)?例如:

     public static void main(String arg[])
     { 
         Thread t1 = new Thread();
         t1.start();
         Thread.Sleep(1000);
     }
    
  2. 如果我在一个线程的方法中调用该方法,当sleep()在main中调用该线程的方法时,它是否也会暂停其他线程?因为这发生在我身上......虽然我知道在这种情况下它应该只暂停它在内部调用的线程例如:run()start()

     //thread Tester has a sleep() in its run() while NoSleep doesn't have
      public static void main(String arg[])
      { 
          Tester t1 = new Tester();
          NoSleep t2 = new NoSleep();
          t1.start();
          t2.start();
     }
    

在这样的代码中,两者都t2暂停,t1我不明白为什么。

4

3 回答 3

2

In Java, threads are all equal peers, without grouping, parenting, or ownership.

So sleeping any one thread has no direct effect on other threads.

Calling Thread.sleep sleeps whatever thread executes that method. Utterly simple, nothing more to explain.

As the Thread.sleep Javadoc says:

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds


By the way, in modern Java we rarely need to address the Thread class directly. Instead we use executor service(s) to execute Runnable or Callable tasks. So no need to call new Thread. And no need to extend from Thread.

于 2021-05-23T16:55:39.053 回答
0

Thread.sleep()是 Java 中许多名称非常糟糕的事物之一。* 不要认为它会“休眠”任何线程。有一个更简单的方法来考虑它:

Thread.sleep(n)什么也没做。

它至少在n几毫秒内什么都不做,然后返回。这就是您需要知道sleep()的全部内容(至少,在您成为 Java 运行时环境的维护者之前,您需要知道的全部内容。)


* Java 是由几个非常聪明的博士发明的。计算机科学家。Java 是一门简单、优美的语言;但是他们为某些对专家来说似乎很明显但有时对初学者来说真的很困惑的东西赋予了名字。

于 2021-05-24T03:05:47.023 回答
0

Thread.sleep() 暂停正在执行代码的当前线程,它对其他线程没有影响。该线程可以是“主”线程或从主线程产生(启动)的线程。

然而 Thread.sleep() 不是实现异步任务的方法,比如暂停一些线程等待 Thread.sleep() 然后猜测在那段时间之后我可以恢复我的线程并希望事件一定是已完成,您的睡眠线程正在等待。您将使用一些低级机制,例如 notify、wait、notifyAll 。而是按照其他答案中的建议使用信号量、倒计时锁存器和其他更好的包装器。在下方评论以获取更多信息或您有疑问,乐于提供帮助

于 2021-05-23T18:12:38.750 回答