java - 在 main 方法中调用 Thread.sleep 方法,它会暂停哪个线程?
问题描述
我对 Thread.sleep() 的工作原理有点困惑:
如果我在 main 方法中调用它,并且还有其他创建的线程正在运行。它会暂停什么:单独的主线程或其所有子线程(将它们视为主线程的一部分)?例如:
public static void main(String arg[]) { Thread t1 = new Thread(); t1.start(); Thread.Sleep(1000); }
如果我在一个线程的方法中调用该方法,当
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
我不明白为什么。
解决方案
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
.
推荐阅读
- python-3.x - 自定义损失函数不能与阈值微分
- laravel - Laravel Passport 不返回不记名令牌
- haskell - Haskell IO 缩进
- php - 如何在 php 中使用 pdo 连接调用 SQL Server 存储过程?
- liferay - Liferay 6.2 到 7.1.1 的迁移
- docker - Docker-Compose 入口点/命令
- java - 使用 for 循环的 Java 阶乘代码未显示准确的输出
- r - 为什么切片函数在不明确使用 dplyr 的情况下不起作用
- sql-server - SQL Server 转到光标所在的下一行
- css - ReactJS:标签无法从远程 url 加载图像并转换提供的 url 失败并出现 404