How to access a Runnable object by Thread?

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

提交回复
热议问题