Java多线程基本问题
当在Java中实例化一个对象时,它是否绑定到实例化的线程?因为当我在一个线程中匿名实现一个接口,并将其传递给另一个线程来运行时,它的所有方法都在原始线程中运行。如果它们绑定到其创建线程,是否可以创建一个将在调用它的任何线程中运行的对象?
When an object is instantiated in Java, is it bound to the thread that instantiated in? Because when I anonymously implement an interface in one thread, and pass it to another thread to be run, all of its methods are run in the original thread. If they are bound to their creation thread, is there anyway to create an object that will run in whatever thread calls it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果线程A创建一个对象:
并且线程B调用该对象上的方法:
那么
run()
方法将在线程中执行> B 。线程A将简单地继续运行它当时正在运行的任何代码。
If thread A creates an object:
and thread B invokes a method on that object:
then the
run()
method will execute in thread B.Thread A will simply keep running whatever code it happens to be running at the time.
该对象未绑定到创建它的线程...在主线程上执行方法的唯一方法是在主线程上调用它们。
相对容易看出哪个线程正在调用该方法...只需创建一个虚拟函数:
在您调用的主线程中:
从您调用的子线程中:
我不确定OP是否使用类似的方式来检测哪个线程线程正在执行该方法,但这是一种方法。
The object is not bound to the thread it was created on... the only way you'll have the methods being executed on the main thread is if you call them on the main thread.
It's relatively easy to see which thread is calling the method... simply make a dummy function:
In the main thread you call:
From the child thread you call:
I'm not sure if the OP is using a similar way to detect which thread is executing the method, but this is one way to do it.