带返回值的对象内的java线程方法

标签 java multithreading methods

我对使用多线程还很陌生,但我想异步调用方法(在单独的线程中)而不是同步调用它。基本思想是,我正在创建一个带有内存中对象的套接字服务器,因此对于每个客户端,我必须异步运行 object.getStuff() 之类的东西。

我发现的两个结构是:

  1. 让类实现 Runnable 并线程化 this
  2. 在方法中声明一个可运行类。

另外这个方法需要一个返回值——是否需要使用ExecutorCallable来实现这个?有人能指出我实现这个的正确方向吗?

我已尝试实现选项 2,但这似乎并未同时处理:

public class Test {
    private ExecutorService exec = Executors.newFixedThreadPool(10);

    public Thing getStuff(){

        class Getter implements Callable<Thing>{
            public Thing call(){
                //do collection stuff
                return Thing;
            }
        }

        Callable<Thing> callable = new Getter();
        Future<Thing> future = exec.submit(callable);
        return future.get();   
    }    
}

我正在为服务器实例化一个测试对象,并为每个客户端连接调用 getStuff()。

最佳答案

线程教程

关于并发的 Java 教程对此有很好的部分。位于https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html 。本质上,您可以实现RunnableCallable,或者继承Thread

子类化线程

您可以编写一个扩展Thread的类,包括匿名内部类。实例化它,然后调用 start() 方法。

public class MyThread extends Thread {
  public void run() {
    System.out.println("This is a thread");
  }
  public static void main(String[] args) {
    MyThread m = new MyThread();
    m.start();
  }
}

实现可运行

您可以编写一个实现Runnable的类,然后将实例包装在Thread中并调用start()。非常像以前的。

public class MyRunnable implements Runnable {
  public void run() {
    System.out.println("This is a thread");
  }
  public static void main(String[] args) {
    MyRunnable r = new MyRunnable();
    (new Thread(r)).start();
  }
}

返回值

Runnable 不允许返回值。如果您需要它,您需要实现 Callable 来代替。 Callable 看起来很像 Runnable,只不过您重写了 call() 方法而不是 run() 方法,并且您需要将其交给 ExecutorService

public class MyCallable implements Callable<Integer> {
  public Integer call() {
    System.out.println("A thread using Callable<Integer>");
    return 42;
  }
  public static void main(String[] args) {
    MyCallable c = new MyCallable();
    Future<Integer> f = Executors.newSingleThreadExecutor().submit(c));
    System.out.println("The thread returned: " +
      f.get());
  }
}

关于带返回值的对象内的java线程方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31539608/

相关文章:

java - 我如何向 :action form 添加数据

java - 如何在json post请求中发送字节数组?

java - 如何同步两个方法

c# - 如何在计时器中使用异步和等待

swift - 是否有其他语言具有类似 Swift 的扩展?

java - 在两个数组中查找值

C# 命名空间通信

Java android 从 imageView 和 TextView 获取一张位图

java - 使用简单的 spring memcached 进行 JSON 序列化

c++ - 使用 C++ 11lambda boost 线程