如何通过线程访问Runnable对象?

Flu*_*ffy 24 java concurrency multithreading

可能重复:need-help-returning-object-in-thread-run-method

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

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?
    }
}
Run Code Online (Sandbox Code Playgroud)

Pla*_*ure 13

我没有看到任何方式在java.lang.Thread文档中这样做.

那么,我最好的答案是,您可能应该使用List<Runnable>而不是(或除此之外)List<Thread>.或者您可能需要某种地图结构,以便您可以从线程访问Runnable.(例如,java.util.HashMap<java.lang.Thread, java.lang.Runnable>)


Pet*_*rey 10

并发库很好地支持了这一点.注意:如果您的任务抛出异常,则在调用get()时,Future将保留此并抛出包装异常

ExecutorService executor = Executors.newSingleThreadedExecutor();

Future<String> future = executor.submit(new Callable<String>() { 
   public String call() { 
      return "world"; 
   } 
}); 

String result = future.get(); 
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望之后关闭执行程序. (2认同)

Igo*_*nov 5

TestRunnable r = new TestRunnable();
Thread t = new Thread(r);
t.start();
//there you need to wait until thread is finished, or just a simple Thread.sleep(1000); at this case
System.out.println(r.foo);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,在实际情况下,您需要使用CallableFutureTask

  • 所以总而言之,没有办法做到,对吧?您需要保留对 Thread 和 Runnable 的引用。如果您能证实您关于需要 Callable 和 FutureTask 的主张,我将不胜感激。 (2认同)
  • 我想我只是没有看到它。 (2认同)