我对使用多线程还很陌生,但我想异步调用方法(在单独的线程
中)而不是同步调用它。基本思想是,我正在创建一个带有内存中对象的套接字服务器,因此对于每个客户端,我必须异步运行 object.getStuff()
之类的东西。
我发现的两个结构是:
- 让类实现 Runnable 并线程化
this
和 - 在方法中声明一个
可运行
类。
另外这个
方法需要一个返回值——是否需要使用Executor
和Callable
来实现这个?有人能指出我实现这个的正确方向吗?
我已尝试实现选项 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 。本质上,您可以实现Runnable
或Callable
,或者继承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/