简体   繁体   English

如何在Java中运行不同的线程?

[英]How do I run different threads in Java?

I'm having some problems with threads. 我遇到线程问题。 I understand how they work, but since they all use the same method, how do I run different threads that do completely different things, but at the same time? 我理解它们是如何工作的,但由于它们都使用相同的方法,我如何运行不同的线程来完成不同的事情,但同时呢?

To me, it seems that they always use the same standard method which makes them do the same thing. 对我来说,似乎他们总是使用相同的标准方法,这使得他们做同样的事情。

So, let's say I have a big .txt file where I want to go through each line and do something to the line. 所以,假设我有一个很大的.txt文件,我想通过每一行并对该行做一些事情。 In this case, I would like to have each thread do 1/10th of the .txt file, but I don't understand how the threads can communicate with each other, and how they could organize so each thread does the right part? 在这种情况下,我想让每个线程执行.txt文件的十分之一,但我不明白线程如何相互通信,以及它们如何组织,以便每个线程做正确的部分?

Could anyone explain or help me with this? 任何人都可以解释或帮助我吗? Would be very much appreciated! 非常感谢!

You can extend java.lang.Thread (or better - implement java.lang.Runnable ) and pass arguments to the constructor of the new object. 您可以扩展java.lang.Thread (或更好 - 实现java.lang.Runnable )并将参数传递给新对象的构造函数。 For the text file example: 对于文本文件示例:

public FileReader implements Runnable {
    private int startLine;
    private int endLine;
    public FileReader(int startLine, int endLine) {
       // assign the params to the fields
    }

    public void run() {
       // use the params to read the appropriate lines
    }
}

and then you can: 然后你可以:

new Thread(new FileReader(1, 10)).start();
new Thread(new FileReader(11, 20)).start();
new Thread(new FileReader(21, 30)).start();

Nowadays you probably should have look at java.util.Concurrent instead of tinkering with primitive threads (although they can of course be used where appropriate). 现在你可能应该看看java.util.Concurrent而不是修改原始线程(尽管它们当然可以在适当的地方使用)。 Threading is quite a big subject, but by using well-defined idioms from the Concurrent package it can become a bit more bearable. 线程是一个很大的主题,但通过使用Concurrent包中明确定义的习语,它可以变得更加可忍受。

As far as i know, threads are independent pieces running in parallel and there is always a master thread (usually Main thread) that controls parallel running worker threads. 据我所知,线程是并行运行的独立部分,并且始终存在控制并行运行的工作线程的主线程(通常是主线程)。 There is no need for threads to communicate with each other since that task is taken care by the Master thread. 由于主线程负责该任务,因此不需要线程彼此通信。

In your case, you can have the Master thread to send arguments to the worker threads stating line numbers - 0 to 10 for thread1, 11 to 20 for thread2 etc. The worker threads take these numbers as input and process the file accordingly. 在您的情况下,您可以让主线程向工作线程发送参数,说明行号 - 对于thread1为0到10,对于thread2等为11到20.工作线程将这些数字作为输入并相应地处理文件。

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

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