简体   繁体   English

在Java中运行执行不同工作的多个线程的正确方法是什么?

[英]What is a correct way to run multiple threads that do different jobs in java?

I am trying to build a network related program in Java. 我正在尝试用Java构建与网络相关的程序。 I have previous experience with C. In C, when you run thread, you define which method you want it to be run as a thread. 我以前有C的经验。在C中,当您运行线程时,可以定义希望它作为线程运行的方法。

However, in Java, it seems that thread always runs with method run() and there can be 1 method with that name in each class. 但是,在Java中,线程似乎总是使用方法run()运行,并且每个类中可以有1个名称相同的方法。

I want to have at least 2 threads, one thread for working on calculations, and one thread to work on communications with other applications. 我希望至少有2个线程,一个用于计算的线程,一个用于与其他应用程序通信的线程。 (Even if this can be done with 1 thread, I just want to know what would be a correct way to run 2 threads that does totally different jobs) (即使这可以用1个线程完成,我只想知道运行两个完全不同的工作的2个线程的正确方法是什么)

Below is just a sample code how I implemented the thread. 以下是我如何实现线程的示例代码。 If thread generated by below codes does communication, what would be a nice way to create another thread that does calculation? 如果下面的代码生成的线程进行通信,那么创建另一个进行计算的线程的一种好方法是什么?

public class Server implements Runnable{

    static Thread myThread;


    public void run() {
        // TODO Auto-generated method stub  
    }

    public static void main(String[] args) {
        myThread = new Thread(new Server());
    }


}

Don't put a main method in the class that implements Thread or Runnable . 不要在实现ThreadRunnable的类中放置main方法。 You could implement what you want with your current Server implementation, but I don't see a good reason to do so. 可以使用当前的Server实现来实现所需的功能,但是我认为这样做没有充分的理由。 Separate out the concerns, and KISS: 分离出关注点,然后KISS:

  • One boring, simple class with a public static void main(String[] args) method 一个无聊的简单类,带有public static void main(String[] args)方法
  • One Server implements Runnable class (one type of thread) 一台Server implements Runnable类(一种线程)
  • One Calculations implements Runnable class (the other type of thread) 一种Calculations implements Runnable类(另一种线程)

The class with the main method would start the Server and Calculations threads. 具有main方法的类将启动ServerCalculations线程。

Use Executors.newSingleThreadExecutor() to create a thread pool containing a single thread. 使用Executors.newSingleThreadExecutor()创建一个包含单个线程的线程池。 Submit Callable objects to this Executor , where each instance will perform one of your calculations. Callable对象提交给此Executor ,每个实例将在其中执行您的计算之一。 A Future object is returned that can be used to fetch the result of the calculation. 返回一个Future对象,该对象可用于获取计算结果。 The calculation itself will be running in a thread managed by the Executor. 计算本身将在执行程序管理的线程中运行。

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

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