How to access a Runnable object by Thread?

前端 未结 11 916
深忆病人
深忆病人 2020-12-08 10:21

Possible duplicate: need-help-returning-object-in-thread-run-method

Hello. I have a class implementing runnable and I have a List, storing Threads instantiated with

相关标签:
11条回答
  • 2020-12-08 11:00

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

    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>)

    0 讨论(0)
  • 2020-12-08 11:00

    You could subclass Thread, and add the method you need. You'll have to keep your own copy of the target Runnable and override all the Thread constructors you use to create the Thread, because of some annoying implementation details of Thread.

    0 讨论(0)
  • 2020-12-08 11:06

    I think in general you can/should avoid doing this, but if you really need to do it shouldn't something like MatrixFrog's suggestion work (untested):

    class RunnableReferencingThread extends Thread {
        public final Runnable runnable;
        public RunnableReferencingThread(Runnable r) {
            super(r);
            this.runnable = r;
        }
    }
    

    ?

    0 讨论(0)
  • 2020-12-08 11:08

    If you want to return the value of an asynchronous calculation, look at Callable and FutureTask:

    FutureTask<String> task = new FutureTask(new Callable<String>() {
       public String call() {
          return "world";
       }
    });
    new Thread(task).start();
    String result = task.get();
    
    0 讨论(0)
  • 2020-12-08 11:09

    If your thread has state information, forget Runnable and simply extend Thread, overriding the run method.

    0 讨论(0)
  • 2020-12-08 11:10

    The concurrency library supports this well. Note: If your task throws an Exception, the Future will hold this and throw a wrapping exception when you call get()

    ExecutorService executor = Executors.newSingleThreadedExecutor();
    
    Future<String> future = executor.submit(new Callable<String>() { 
       public String call() { 
          return "world"; 
       } 
    }); 
    
    String result = future.get(); 
    
    0 讨论(0)
提交回复
热议问题