gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:13:00 24 4
gpt4 key购买 nike

我对使用多线程还很陌生,但我想异步调用方法(在单独的线程中)而不是同步调用它。基本思想是,我正在创建一个带有内存中对象的套接字服务器,因此对于每个客户端,我必须异步运行 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com