首页 > 解决方案 > 在 main 方法中调用 Thread.sleep 方法,它会暂停哪个线程?

问题描述

我对 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我不明白为什么。

标签: javamultithreadingsleepthread-sleep

解决方案


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.


推荐阅读