Java多线程基本问题

发布于 2024-08-24 22:58:15 字数 125 浏览 5 评论 0原文

当在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我们只是彼此的过ke 2024-08-31 22:58:15

如果线程A创建一个对象:

MyClass.staticMember = new Runnable() {...};

并且线程B调用该对象上的方法:

MyClass.staticMember.run();

那么run()方法将在线程中执行> B 。

线程A将简单地继续运行它当时正在运行的任何代码。

If thread A creates an object:

MyClass.staticMember = new Runnable() {...};

and thread B invokes a method on that object:

MyClass.staticMember.run();

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.

小红帽 2024-08-31 22:58:15

该对象未绑定到创建它的线程...在主线程上执行方法的唯一方法是在主线程上调用它们。

相对容易看出哪个线程正在调用该方法...只需创建一个虚拟函数:

public threadDetect(string which)
{
    System.out.println("Executed from " + which + " thread.");
}

在您调用的主线程中:

threadDetect("main");

从您调用的子线程中:

threadDetect("child");

我不确定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:

public threadDetect(string which)
{
    System.out.println("Executed from " + which + " thread.");
}

In the main thread you call:

threadDetect("main");

From the child thread you call:

threadDetect("child");

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文