如何在Java中使用单独的线程调用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3489543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a method with a separate thread in Java?
提问by Louis Rhys
let's say I have a method doWork()
. How do I call it from a separate thread (not the main thread).
假设我有一个方法doWork()
。我如何从一个单独的线程(不是主线程)调用它。
采纳答案by Noel M
Create a class that implements the Runnable
interface. Put the code you want to run in the run()
method - that's the method that you must write to comply to the Runnable
interface. In your "main" thread, create a new Thread
class, passing the constructor an instance of your Runnable
, then call start()
on it. start
tells the JVM to do the magic to create a new thread, and then call your run
method in that new thread.
创建一个实现Runnable
接口的类。将您要运行的代码放在run()
方法中 - 这是您必须编写以符合Runnable
接口的方法。在您的“主”线程中,创建一个新Thread
类,将您的 实例传递给构造函数Runnable
,然后调用start()
它。start
告诉 JVM 创建一个新线程,然后run
在该新线程中调用您的方法。
public class MyRunnable implements Runnable {
private int var;
public MyRunnable(int var) {
this.var = var;
}
public void run() {
// code in the other thread, can reference "var" variable
}
}
public class MainThreadClass {
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable(10);
Thread t = new Thread(myRunnable)
t.start();
}
}
Take a look at Java's concurrency tutorialto get started.
查看Java 的并发教程以开始使用。
If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at Future
, Callable
, Executor
classes in the java.util.concurrent
package.
如果您的方法将被频繁调用,那么每次都创建一个新线程可能不值得,因为这是一项昂贵的操作。最好使用某种线程池。查看包中的Future
, Callable
,Executor
类java.util.concurrent
。
回答by raja kolluru
Sometime ago, I had written a simple utility class that uses JDK5 executor service and executes specific processes in the background. Since doWork() typically would have a void return value, you may want to use this utility class to execute it in the background.
前段时间写了一个简单的实用类,使用JDK5执行器服务,在后台执行特定的进程。由于 doWork() 通常会有一个 void 返回值,您可能希望使用此实用程序类在后台执行它。
See this articlewhere I had documented this utility.
请参阅我记录此实用程序的这篇文章。
回答by MANN
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
});
t1.start();
or
或者
new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
}).start();
or
或者
new Thread(() -> {
// code goes here.
}).start();
or
或者
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
or
或者
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
回答by Aaron Cohn
In Java 8 you can do this with one line of code.
在 Java 8 中,您可以使用一行代码完成此操作。
If your method doesn't take any parameters, you can use a method reference:
如果您的方法不带任何参数,则可以使用方法引用:
new Thread(MyClass::doWork).start();
Otherwise, you can call the method in a lambda expression:
否则,您可以在 lambda 表达式中调用该方法:
new Thread(() -> doWork(someParam)).start();
回答by Rohan Sawant
Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression
调用事物(例如 DialogBoxes 和 MessageBoxes 并为非线程安全方法创建单独的线程)的另一个更快的选择是使用 Lamba 表达式
new Thread(() -> {
"code here"
}).start();
回答by Clyde
To achieve this with RxJava 2.x you can use:
要使用 RxJava 2.x 实现这一点,您可以使用:
Completable.fromAction(this::dowork).subscribeOn(Schedulers.io().subscribe();
The subscribeOn()
method specifies which scheduler to run the action on - RxJava has several predefined schedulers, including Schedulers.io()
which has a thread pool intended for I/O operations, and Schedulers.computation()
which is intended for CPU intensive operations.
该subscribeOn()
方法指定在哪个调度程序上运行操作——RxJava 有几个预定义的调度程序,包括Schedulers.io()
哪些具有用于 I/O 操作的线程池,以及Schedulers.computation()
用于 CPU 密集型操作的线程池。
回答by k13i
If you are using at least Java 8 you can use method runAsync
from class CompletableFuture
如果您至少使用 Java 8,则可以使用CompletableFuturerunAsync
类中的方法
CompletableFuture.runAsync(() -> {...});
If you need to return a result use supplyAsync
instead
如果您需要返回结果,请supplyAsync
改用
CompletableFuture.supplyAsync(() -> 1);