简体   繁体   English

如何从后台线程调用Java类

[英]How to call a Java class from a background thread

I need to call this class from a background thread. 我需要从后台线程调用此类。

ChartPenData.main(arguments);

How can I do that? 我怎样才能做到这一点?

Thread thread = new Thread();
thread = ChartPenData.main(arguments);
thread.run();
new Thread() {
  public void run() {ChartPenData.main(arguments);}
}.start();

But better to have a class implement runnable, which takes arguments as constructor parameters, and store it as member variable to use inside run() method. 但是最好让类实现可运行,该类将参数作为构造函数参数,并将其存储为成员变量以在run()方法中使用。 Then you would do: 然后,您将执行以下操作:

new Thread(myRunnable).start();
Thread t = new Thread() {
    public void run() {
        ChartPenData.main(arguments);
    }
};
t.start();

The easiest safe way to do that is using java.util.concurrent.ExecutorService. 最简单的安全方法是使用java.util.concurrent.ExecutorService。

You can use java.util.concurrent.Executors utility methods to create ExecutorService's 您可以使用java.util.concurrent.Executors实用程序方法创建ExecutorService的

example: 例:

 private final ExecutorService executorService = Executors.newSingleThreadExecutor();
 executorService.submit( new Runnable() {

        @Override
        public void run()
        {
            ChartPenData.main(arguments);                
        }
    } );

This should give you a fair idea about what you are trying to achieve 这应该使您对要实现的目标有一个清晰的认识

    public class Tester {
       public static void main(String args[]) {
          String[] arguments = {"param1", "param2"};
          Thread t = new Thread(new ClassCaller(arguments));
          t.start();
       }
    }

    class ClassCaller implements Runnable {
       private String[] arguments;
       public ClassCaller(String[] args) {
          arguments = args;
       }
       public void run() {
         ChartPenData.main(arguments);
       }
    }

class ChartPenData {
//your class code goes here
}

Your example code doesn't make much sense: 您的示例代码没有多大意义:

  • It creates a Thread that doesn't do anything. 它创建一个不执行任何操作的Thread
  • It assigns the same variable two times without ever using the value of the variable in between. 它两次分配相同的变量,而没有使用两次之间的变量值。
  • It calls a function as if the function was going to return a Thread (and, I'm guessing from the name of the function that that's not what it does) when you say you want to call the function in a thread. 当您说要线程中调用该函数时,它就像调用该函数将要返回一个Thread一样调用函数(并且,我从函数名称中猜测这不是它的功能)。

Other answers here show you what you asked for, but IMO, you would be better off learning more of the basics of Java (classes, types, variables, method calls, etc.) before you attempt to learn anything about threads. 此处的其他答案显示了您的要求,但是IMO最好在尝试学习有关线程的知识之前学习更多Java基础知识(类,类型,变量,方法调用等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM