如何通过线程访问 Runnable 对象? [英] How to access a Runnable object by Thread?

查看:28
本文介绍了如何通过线程访问 Runnable 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:need-help-returning-object-in-线程运行方法

你好.我有一个实现 runnable 的类,我有一个 List,用于存储用该类的不同对象实例化的线程.给定运行它们的线程对象,如何访问底层对象的属性?下面是一个例子:

Hello. I have a class implementing runnable and I have a List, storing Threads instantiated with different objects of that class. How can I access properties of underlying objects given the thread object running them? Here is an example:

public class SO {
    public static class TestRunnable implements Runnable {
        public String foo = "hello";

        public void run() {
            foo = "world";
        }
    }

    public static void main(String[] args) {
        Thread t = new Thread(new TestRunnable());
        t.start();
        //How can I get the value of `foo` here?
    }
}

推荐答案

我在 java.lang.Thread 文档.

I don't see any way to do it in the java.lang.Thread docs.

我最好的答案是,您可能应该使用 List 而不是(或除此之外)List.或者你可能想要某种 map 结构,以便您可以从线程访问 Runnable.(例如,java.util.HashMap)

My best answer, then, is that you probably should be using List<Runnable> instead of (or in addition to) List<Thread>. Or perhaps you want some sort of map structure so that you can access the Runnable from the Thread. (For example, java.util.HashMap<java.lang.Thread, java.lang.Runnable>)

这篇关于如何通过线程访问 Runnable 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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