如何在Java中使用单独的线程调用方法? [英] How to call a method with a separate thread in Java?

查看:37
本文介绍了如何在Java中使用单独的线程调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个方法 doWork().我如何从一个单独的线程(不是主线程)调用它.

解决方案

创建一个实现 Runnable 接口的类.将您要运行的代码放在 run() 方法中 - 您必须编写该方法以符合 Runnable 接口.在您的主"线程中,创建一个新的 Thread 类,将您的 Runnable 的实例传递给构造函数,然后对其调用 start().start 告诉 JVM 创建一个新线程,然后在该新线程中调用您的 run 方法.

public class MyRunnable 实现 Runnable {私有整数变量;公共 MyRunnable(int var) {this.var = var;}公共无效运行(){//其他线程中的代码,可以引用var"变量}}公共类 MainThreadClass {公共静态无效主(字符串参数[]){MyRunnable myRunnable = new MyRunnable(10);线程 t = 新线程(myRunnable)t.start();}}

查看 Java 的并发教程以开始使用.>

如果你的方法会被频繁调用,那么每次都创建一个新线程可能不值得,因为这是一个昂贵的操作.最好使用某种线程池.查看 java.util.concurrent 包中的 FutureCallableExecutor 类.

let's say I have a method doWork(). How do I call it from a separate thread (not the main thread).

解决方案

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();
    }    
}

Take a look at Java's concurrency tutorial to get started.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆