如何在Java中使用单独的线程调用方法?
2022-08-31 07:25:14
假设我有一种方法。如何从单独的线程(而不是主线程)调用它。doWork()
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
});
t1.start();
或
new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
}).start();
或
new Thread(() -> {
// code goes here.
}).start();
或
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
或
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
创建一个实现接口的类。将要运行的代码放在方法中 - 这是您必须编写以符合接口的方法。在“主”线程中,创建一个新类,向构造函数传递一个 实例,然后调用它。 告诉 JVM 执行魔术来创建新线程,然后在该新线程中调用您的方法。Runnable
run()
Runnable
Thread
Runnable
start()
start
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();
}
}
查看 Java 的并发教程以开始使用。
如果您的方法将被频繁调用,那么可能不值得每次都创建一个新线程,因为这是一个代价高昂的操作。最好使用某种线程池。查看包中的 、 、 类。Future
Callable
Executor
java.util.concurrent