将单个runnable对象传递给多个线程构造函数 [英] Passing single runnable object to multiple thread constructors

查看:142
本文介绍了将单个runnable对象传递给多个线程构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个可运行的对象

If I create a runnable object

Runnable run = new MyRunnable();

然后将同一个确切的对象传递给两个线程构造函数并运行它们

And then pass the same exact object to two thread constructors and run them

new Thread(run).start;
new Thread(run).start;




  1. 可能吗?有什么影响?

  2. 如果我调用Thread.sleep(0);在MyRunnable类中,两个线程都会因为它们是同一个对象而睡眠,还是线程实体与对象完全分离?

  3. 是否有理由这样做,如果没有请仍然回答上面的两个问题,因为我不认为我完全理解线程机制了吗?


推荐答案


  1. 这绝对可行且合法。如果你的 Runnable 没有状态(没有字段),那么一切都会好的。如果您的 Runnable 确实具有可变状态,那么您可能需要使用Java的许多互斥机制,如 ReentrantLock synchronized 关键字。因为两个线程都会改变相同 Runnable 对象的字段。

  1. It's definitely possible and legal. If your Runnable has no state (no fields), then everything will be fine. If your Runnable does have mutable state, then you may need to use one of Java's many mutual exclusion mechanisms like ReentrantLock or the synchronized keyword. Because both Threads will be mutating the fields of the same Runnable object.

不,你创建了跑了两个不同的主题。他们只需调用 Runnable.run()

No, you created and ran two different Threads. They simply call Runnable.run().

这不是可能的范围。我甚至不会说这一定是不好的做法。你可以这样做的具体情况留给读者作为练习......

It's not out of the realm of possibility. I wouldn't even say it's necessarily bad practice. Specific situations where you might do this left as an exercise to the reader...

这篇关于将单个runnable对象传递给多个线程构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆