阻止其他线程运行一段代码
我想阻止其他线程(非法线程)运行run()
。解决方案是:
public class MyThread extends Thread {
public void run() {
if (currentThread() != this)
throw new IllegalStateException("Exception occurred by: " + currentThread().toString());
/* Here goes the main logic of thread */
}
}
当MyThread
类直接实现Runnable
时,我们如何做同样的事情?
I want to prevent to other threads(illegal threads) from running run()
. the solution is:
public class MyThread extends Thread {
public void run() {
if (currentThread() != this)
throw new IllegalStateException("Exception occurred by: " + currentThread().toString());
/* Here goes the main logic of thread */
}
}
How could we do the same thing when MyThread
class is directly implementing Runnable
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需存储对
Thread
的引用,该线程允许作为Runnable
类中的成员运行代码。在比较中使用它。Simply store a reference to the
Thread
that is allowed to run the code as a member in yourRunnable
class. Use that in the comparison.