如何在Java中使用单独的线程调用方法? [英] How to call a method with a separate thread in Java?
问题描述
假设我有一个方法 doWork()
。如何从单独的线程(而不是主线程)调用它。
let's say I have a method doWork()
. How do I call it from a separate thread (not the main thread).
推荐答案
创建一个实现<$ c的类$ c> Runnable 界面。将您想要运行的代码放在 run()
方法中 - 这是您必须编写的方法,以符合 Runnable
界面。在主线程中,创建一个新的 Thread
类,将构造函数传递给 Runnable
的实例,然后调用 start()
就可以了。 start
告诉JVM创建一个新线程,然后在该新线程中调用 run
方法。
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.
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();
}
}
看看 Java的并发教程开始使用。
如果你的方法将被频繁调用,然后每次创建一个新线程可能都不值得,因为这是一个昂贵的操作。最好使用某种线程池。看一下 Future
, Callable
, Executor
中的类 java.util.concurrent
包。
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.
这篇关于如何在Java中使用单独的线程调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!