如何从runnable线程获取返回值而不是使用join进行阻塞?

时间:2014-08-07 02:19:50

标签: java multithreading

如何在不使用join的情况下获取返回值(因为在这种情况下会阻塞)或使用类变量来保存结果?

或者我怎样才能使这个异步wiit java 6/7和spring 3.2.3?

   public String createStuffPublic (final String stuffId) {
        Thread t = new Thread(new Runnable() { public void run() {
            try {
                // long running method to get a string...stored in class variable
                _output = createStuffPrivate(final String stuffId);
            }
            catch (Exception e) {
              // err
            }
        } });
        t.start();
        t.join();  // this blocks so really can't use it to get the result
        return _output;
   }

   public void driverSimulatedMultiClientCallMethod() {
       ...
       // no blocking want to execute in parallel
       for (int i=0; i<numClients; i++) {
         String output = singleton.createStuffPublic ("client" + i);
         System.out.println("output for client" + i + ": " + output);    
       }
   }