java - 如果线程只能访问具有自己实例(由不同线程创建)的类的静态方法,那么它将在哪个线程上执行?

标签 java android multithreading runnable ui-thread

假设我有一个带有 2 个公共(public)静态方法的类,这些方法控制其自身的单个私有(private)实例。该类的基本结构如下:

public class MyClass {
    private static MyClass myclass = null;
    private final Process, OutputStreamWriter, Strings, ints, etc....
    private class constructor....    
    private class methods....  
        
    public static void command(String cmd) {
        if(myclass == null) {
            myclass = new MyClass();
        }
        myclass.setCmd(cmd);
    }
    
    public static void execute() {
        myclass.run();
        myclass.close();
    }
}

我在 Android 应用程序中使用它,我只是想在深入设计之前验证它是如何工作的。假设该类的命令来自 UI 线程。 UI线程调用第一个静态方法

MyClass.command("parse and do what's in this string");

现在我预计 MyClass.execute() 调用在某些情况下可能需要几乎一秒钟才能完成。我基本上只是想验证如果我从 Service 或 Runnable 调用 MyClass.execute() 方法,执行将在该线程上发生。

在帖子中static-method-behavior-in-multi-threaded-environment-in-java塞利格指出:

Memory in java is split up into two kinds - the heap and the stacks. The heap is where all the objects live and the stacks are where the threads do their work. Each thread has its own stack and can't access each others stacks. Each thread also has a pointer into the code which points to the bit of code they're currently running.

When a thread starts running a new method it saves the arguments and local variables in that method on its own stack. Some of these values might be pointers to objects on the heap. If two threads are running the same method at the same time they will both have their code pointers pointing at that method and have their own copies of arguments and local variables on their stacks....

现在,由于 UI 线程调用了静态方法 MyClass.command("Do this"),该方法从技术上实例化了该类的私有(private)局部参数和变量,这是否意味着该类位于 UI 线程的堆???这意味着如果我从服务线程或可运行线程调用 MyClass.execute(),实际执行将在服务或可运行线程等待时在 UI 线程上发生?我的理解正确吗?

谢谢!

最佳答案

好吧,您的帖子中有很多错误信息。

1) 默认情况下,Services 和 Runnables 没有自己的线程。服务在 UI 线程上运行,尽管它们可以创建线程(默认情况下 IntentService 会这样做)。 Runnables 在任何线程调用上运行。但是,除非您将它们发布到附加到另一个线程或 Thread 对象的处理程序,否则它们不会启动新的处理程序。

2)所有的Java对象都在堆上,而不是在栈上。堆栈仅保存原始类型和对对象的引用(但对象本身位于堆上)。

3)是的,每个线程都有自己的堆栈,因此它可以有自己的一组局部变量。但这并不能阻止它接触堆上的任何东西。这包括程序中的任何对象

4) 线程唯一私有(private)的是函数中的局部变量。请注意,任何本地对象仍在堆上,并且可以保存对它的引用并将其传递给另一个线程。

5) 绝对没有任何东西可以限制线程仅调用静态方法。您可以调用任何您想要的类型的方法。

关于java - 如果线程只能访问具有自己实例(由不同线程创建)的类的静态方法,那么它将在哪个线程上执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472386/

相关文章:

android - 什么是本地 android SDK 中的 m2repository 文件夹?

java - 如何迭代动态创建的对象?

java - 如何知道 CompletionService 何时完成交付结果?

c - 在多线程程序中将全局数组锁定在需要重入的函数中?

java - 在 Java 中暂停线程?

java - Servlet 3.0 异步

java - mysql使用servlet更新用户信息的方法

java - 使用 Java 通过 SSH 同步 MySQL 数据库

java - 在android中将字符串转换为bigdecimal

android - 这是普通的 Android 通知 (RemoteView) 布局吗?