简体   繁体   English

基本Java多线程问题

[英]Basic Java Multi-Threading Question

When an object is instantiated in Java, is it bound to the thread that instantiated in? 用Java实例化对象时,它是否绑定到实例化的线程? 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? 如果将它们绑定到其创建线程,是否仍然可以创建将在任何线程调用中运行的对象?

If thread A creates an object: 如果线程A创建了一个对象:

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

and thread B invokes a method on that object: 线程B在该对象上调用一个方法:

MyClass.staticMember.run();

then the run() method will execute in thread B . 然后run()方法将在线程B中执行。

Thread A will simply keep running whatever code it happens to be running at the time. 线程A只会继续运行当时恰巧正在运行的任何代码。

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. 我不确定OP是否正在使用类似的方式来检测哪个线程正在执行该方法,但这是一种实现方式。

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

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