java Runnable run()方法返回一个值

时间:2022-11-30 17:33:05

According to java doc, Runnable method void run() cannot return a value. I do wonder however if there is any workaround of this.

Actually i have a method which calls:

根据java doc,Runnable方法void run()不能返回值。我不知道是否有任何解决方法。其实我有一个调用的方法:

public class Endpoint{
    public method_(){
       RunnableClass runcls = new RunnableClass();
       runcls.run()
    }
}

wheren method run() is:

方法run()是:

public class RunnableClass implements Runnable{

    public jaxbResponse response;
        public void run() {
            int id;
            id =inputProxy.input(chain);
            response = outputProxy.input();

        }
}

I want to have acces to response variable in method_() is this possible?

我想在method_()中访问响应变量这可能吗?

8 个解决方案

#1


47  

Use Callable<V> instead of using Runnable interface.

使用Callable 而不是使用Runnable接口。

Example:

public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future<Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }

In this example, you will also need to implement the class WordLengthCallable, which implements the Callable interface.

在此示例中,您还需要实现WordLengthCallable类,该类实现Callable接口。

#2


13  

public void check() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Integer> result = executor.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            return 10;
        }
    });

    try {
        int returnValue = result.get();
    } catch (Exception exception) {
       //handle exception
    }
}

#3


6  

Have a look at the Callable class. This is usually submited via an executor service

看看Callable类。这通常通过执行程序服务提交

It can return a future object which is returned when the thread completes

它可以返回线程完成时返回的future对象

#4


3  

If you add a field to RunnableClass you can set it in run and read it in method_. However, Runnable is a poor (the Java keyword) interface as it tells you nothing about the (the concept) interface (only useful line of the API docs: "The general contract of the method run is that it may take any action whatsoever."). Much better to use a more meaningful interface (that may return something).

如果向RunnableClass添加字段,可以在运行中设置它并在method_中读取它。但是,Runnable是一个糟糕的(Java关键字)接口,因为它没有告诉你任何关于(概念)接口的信息(只有API文档的有用行:“方法运行的一般合同是它可能采取任何行动。 “)。使用更有意义的界面(可能会返回一些东西)会好得多。

#5


1  

One way is, we have to use Future - Callable approach.

一种方法是,我们必须使用Future - Callable方法。

Another way is, Instead of returning value, you can hold in object

另一种方法是,您可以保留对象,而不是返回值

Example:

class MainThread {
    public void startMyThread() {
        Object requiredObject = new Object(); //Map/List/OwnClass
        Thread myThread = new Thread(new RunnableObject(requiredObject)).start();
        myThread.join();

        System.out.println(requiredObject.getRequiredValue());    
    }
}



class RunnableObject implements Runnable {
    private Object requiredObject;

    public RunnableObject(Object requiredObject) {
        this.requiredObject = requiredObject;
    }

    public void run() {
        requiredObject.setRequiredValue(xxxxx);
    }
}

Because object scope is in the same scope so that you can pass object to thread and can retrieve in the main scope. But, most important thing is, we have to use join() method. Because main scope should be waiting for thread completion of its task.

因为对象范围在同一范围内,所以您可以将对象传递给线程并可以在主范围内检索。但是,最重要的是,我们必须使用join()方法。因为主要范围应该等待线程完成其任务。

For multiple thread case, you can use List/Map to hold the values from threads.

对于多线程情况,您可以使用List / Map来保存线程中的值。

#6


0  

Take a look at the callable interface, perhaps this suites your needs. You can also try to get the value of the response field by calling a setter-method inside of your run() method

看看可调用的界面,也许这可以满足您的需求。您还可以通过调用run()方法中的setter方法来尝试获取响应字段的值

public void run() {
    int id;
    id =inputProxy.input(chain);
    response = outputProxy.input();
    OuterClass.setResponseData(response);

}

#7


0  

Yes, there are workaround. Just use queue and put into it value which you want to return. And take this value from another thread.

是的,有解决方法。只需使用队列并输入您想要返回的值。并从另一个线程中获取此值。

public class RunnableClass implements Runnable{

        private final BlockingQueue<jaxbResponse> queue;


        public RunnableClass(BlockingQueue<jaxbResponse> queue) {
            this.queue = queue;
        }

        public void run() {
            int id;
            id =inputProxy.input(chain);
            queue.put(outputProxy.input());
        }
    }


    public class Endpoint{
        public method_(){
            BlockingQueue<jaxbResponse> queue = new LinkedBlockingQueue<>();

            RunnableClass runcls = new RunnableClass(queue);
            runcls.run()

            jaxbResponse response = queue.take(); // waits until takes value from queue
        }
    }

#8


0  

Try the following

请尝试以下方法

public abstract class ReturnRunnable<T> implements Runnable {

    public abstract T runForResult();

    @Override
    public void run() {
        runForResult();
    }
}

#1


47  

Use Callable<V> instead of using Runnable interface.

使用Callable 而不是使用Runnable接口。

Example:

public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future<Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }

In this example, you will also need to implement the class WordLengthCallable, which implements the Callable interface.

在此示例中,您还需要实现WordLengthCallable类,该类实现Callable接口。

#2


13  

public void check() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Integer> result = executor.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            return 10;
        }
    });

    try {
        int returnValue = result.get();
    } catch (Exception exception) {
       //handle exception
    }
}

#3


6  

Have a look at the Callable class. This is usually submited via an executor service

看看Callable类。这通常通过执行程序服务提交

It can return a future object which is returned when the thread completes

它可以返回线程完成时返回的future对象

#4


3  

If you add a field to RunnableClass you can set it in run and read it in method_. However, Runnable is a poor (the Java keyword) interface as it tells you nothing about the (the concept) interface (only useful line of the API docs: "The general contract of the method run is that it may take any action whatsoever."). Much better to use a more meaningful interface (that may return something).

如果向RunnableClass添加字段,可以在运行中设置它并在method_中读取它。但是,Runnable是一个糟糕的(Java关键字)接口,因为它没有告诉你任何关于(概念)接口的信息(只有API文档的有用行:“方法运行的一般合同是它可能采取任何行动。 “)。使用更有意义的界面(可能会返回一些东西)会好得多。

#5


1  

One way is, we have to use Future - Callable approach.

一种方法是,我们必须使用Future - Callable方法。

Another way is, Instead of returning value, you can hold in object

另一种方法是,您可以保留对象,而不是返回值

Example:

class MainThread {
    public void startMyThread() {
        Object requiredObject = new Object(); //Map/List/OwnClass
        Thread myThread = new Thread(new RunnableObject(requiredObject)).start();
        myThread.join();

        System.out.println(requiredObject.getRequiredValue());    
    }
}



class RunnableObject implements Runnable {
    private Object requiredObject;

    public RunnableObject(Object requiredObject) {
        this.requiredObject = requiredObject;
    }

    public void run() {
        requiredObject.setRequiredValue(xxxxx);
    }
}

Because object scope is in the same scope so that you can pass object to thread and can retrieve in the main scope. But, most important thing is, we have to use join() method. Because main scope should be waiting for thread completion of its task.

因为对象范围在同一范围内,所以您可以将对象传递给线程并可以在主范围内检索。但是,最重要的是,我们必须使用join()方法。因为主要范围应该等待线程完成其任务。

For multiple thread case, you can use List/Map to hold the values from threads.

对于多线程情况,您可以使用List / Map来保存线程中的值。

#6


0  

Take a look at the callable interface, perhaps this suites your needs. You can also try to get the value of the response field by calling a setter-method inside of your run() method

看看可调用的界面,也许这可以满足您的需求。您还可以通过调用run()方法中的setter方法来尝试获取响应字段的值

public void run() {
    int id;
    id =inputProxy.input(chain);
    response = outputProxy.input();
    OuterClass.setResponseData(response);

}

#7


0  

Yes, there are workaround. Just use queue and put into it value which you want to return. And take this value from another thread.

是的,有解决方法。只需使用队列并输入您想要返回的值。并从另一个线程中获取此值。

public class RunnableClass implements Runnable{

        private final BlockingQueue<jaxbResponse> queue;


        public RunnableClass(BlockingQueue<jaxbResponse> queue) {
            this.queue = queue;
        }

        public void run() {
            int id;
            id =inputProxy.input(chain);
            queue.put(outputProxy.input());
        }
    }


    public class Endpoint{
        public method_(){
            BlockingQueue<jaxbResponse> queue = new LinkedBlockingQueue<>();

            RunnableClass runcls = new RunnableClass(queue);
            runcls.run()

            jaxbResponse response = queue.take(); // waits until takes value from queue
        }
    }

#8


0  

Try the following

请尝试以下方法

public abstract class ReturnRunnable<T> implements Runnable {

    public abstract T runForResult();

    @Override
    public void run() {
        runForResult();
    }
}