简体   繁体   English

从Runnable内部访问线程

[英]Access Thread from inside Runnable

How can I access Thread object that is executing given Runnable ? 如何访问在给定Runnable执行的Thread对象? What I'd like to do is to call sleep() from within run() method. 我想做的是从run()方法中调用sleep()

If you need to sleep within a Runnable , you can simply call Thread.sleep(); 如果你需要在Runnable睡觉,你可以简单地调用Thread.sleep(); inside the run method. run方法中。

To access the thread that is running the Runnable , you can call Thread.currentThread() , but that is not necessary to call the sleep method, which is static. 要访问运行Runnable的线程,可以调用Thread.currentThread() ,但不需要调用sleep方法,这是静态的。

you can always get the current Thread that your code is executing within by calling the static method Thread.currentThread() . 通过调用静态方法Thread.currentThread() ,您始终可以获得代码正在执行的当前Thread

But in your case, you don't need the thread itself because sleeping is controlled with the following static method: 但在您的情况下,您不需要线程本身,因为使用以下静态方法控制休眠:

Thread.sleep(1000L);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM