How to access a Runnable object by Thread?

前端 未结 11 920
深忆病人
深忆病人 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:16

    I had the same problem. Here is my solution:

    public static class TestRunnable implements Runnable {
        public String foo = "hello";
    
        public void run() {
            foo = "world";
        }
    
    public static void main(String[] args) {
        TestRunnable runobject = new TestRunnable();
        Thread t = new Thread(runobject);
        runobject.foo;  //The variable from runnable. hello;
        t.start();
        runobject.foo;  //The variable from runnable. world;
    }
    
    0 讨论(0)
  • 2020-12-08 11:17

    To give a concrete example of Paul Crowley's solution, I think this is what he suggests:

    public class BackgroundJob<JOB extends Runnable> extends Thread {
    
        private final JOB mJob;
    
        public BackgroundJob(JOB job) {
            super(job);
            mJob = job;
        }
    
        public JOB getJob() {
            return mJob;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-08 11:21

    This is how you could implement this directly.

    public static void main(String[] args) {
        // Keep a reference to the runnable object for later ...
        TestRunnable r = new TestRunnable();
        Thread t = new Thread(r);
        t.start();
        // Wait until the child thread has finished
        t.join();
        // Pull the result out of the runnable.
        System.out.println(r.foo);
    }
    

    However, the modern (less error prone) way to do this kind of thing is to use the higher-level concurrency classes in java.util.concurrent.

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

    I think, if you can, it is to revert the situation. Then in this case a good solution is to store the thread in your runnable class. And your runnable has a start() function that launch and start itself the local thread and call thread.start. Like this you can have a list of your threaded objects. Also you can have an accessor to get the thread.

    public class Threaded extends other implements Runnable {
        Thread localThread;
    
        @Override
        public void run() {
            //...
        }
    
        public void start() {
            localThread = new Thread(this);
            localThread.start();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-08 11:22
    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);
    

    BTW, in real case you need to use Callable and FutureTask

    0 讨论(0)
提交回复
热议问题