简体   繁体   English

Java:将参数传递给另一个线程的线程

[英]Java: Thread passing parameters to another thread

I have two java classes called Reader and Worker. 我有两个名为Reader和Worker的java类。 Reader reads strings from a text file and passes these strings to Workers which sort these strings into a tree. Reader从文本文件中读取字符串,并将这些字符串传递给Workers,这些字符串将这些字符串排序为树。 So I create a number of Worker-threads and 1 Reader-thread: 所以我创建了许多Worker-threads和1个Reader-thread:

        try {      

        /* Create and run worker processes. */
        workers = new TrieWorker[numberOfWorkers];
        for(int i = 0; i < numberOfWorkers; i++)
        {
            workers[i] = new TrieWorker(this);
            new Thread(workers[i]).run();
        }

        /* Create and run reader process. */
        reader  = new TrieReader(this, filename);                        
        new Thread(reader).run();

    } catch(Exception e) {
        e.printStackTrace();
    }

When my Reader reads a string from a text file inside run()-method, it passes the string to one of the workers by calling 当我的Reader从run() - 方法内的文本文件中读取字符串时,它通过调用将字符串传递给其中一个worker

workers[i].add(string);

Workers are basically doing nothing until this method has been called. 在调用此方法之前,工人基本上什么都不做。 So I'm wondering, does Reader continue reading from a text file immediately after it passes this parameter to one of the Workers? 所以我想知道,Reader在将此参数传递给其中一个Worker之后会立即继续从文本文件中读取吗? Or does it return from this method only after Worker is done with the string? 或者只有在完成字符串后,它才会从此方法返回? In other words, when one Thread passes parameters to another one, do they both continue to do their own thing unless Thread passing parameters wants some kind of an answer back? 换句话说,当一个Thread将参数传递给另一个时,除非Thread传递参数需要某种回答,否则它们都会继续做自己的事情吗?

Hope you guys know what I mean, really hard to explain. 希望你们知道我的意思,真的很难解释。

EDIT: Thanks for the good answers! 编辑:谢谢你的好答案! Here's code of Reader class: 这是Reader类的代码:

private static int numberOfNextWorker = 0;

    public void run() 
{
    System.out.println("Reader run.");

    try {
        System.out.println("Reading " + filename);
        read();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public void read() throws Exception
{
    File file = new File(filename);
    Scanner reader = new Scanner(file);

    if(file.canRead() == false)
        throw new Exception("file " + filename + " cannot be read.");

    long totalLength = file.length();

    while(reader.hasNextLine())
    {

            String text = reader.nextLine();          
            numberOfLines++;

            /* Passes the work on to workers. */
            if(numberOfNextWorker == (numberOfWorkers - 1))
                 numberOfNextWorker = 0;
            else
                 numberOfNextWorker++;

            workers[numberOfNextWorker].add(text); 
        }
}

And here Worker: 在这里工人:

    public void run() 
{
    System.out.println("Worker run.");
}

void add(String text) 
{
    numberOfStrings++;
    char[] chars = text.toCharArray();

    int i = 0;
    Node node = new Node();

    while (chars.length > i) {
        node.value = chars[i];
        node = node.children;
        i++;
    }
}

It's not doing anything wise yet :) I think I understood what you said. 它没有做任何明智的事情:)我想我理解你所说的。 I have read this book about concurrency a lot and done some exercises on paper but haven't tried to code anything that much. 我已经阅读了很多关于并发性的书,并在纸上做了一些练习,但没有尝试过那么多的代码。

Note that you are not starting a new thread at any point, but only call the run() method on the same thread. 请注意,您不是在任何时候启动新线程,而是仅在同一线程上调用run()方法。

You need to call to start() to spawn a new thread, for example: 你需要调用start()来生成一个新线程,例如:

new Thread(workers[i]).start();

instead of 代替

new Thread(workers[i]).run();

How specifically the threads will continue working depends on your implementation. 线程如何继续工作取决于您的实现。

The call to Worker.add is blocking, so it waits until add() is done. 对Worker.add的调用是阻塞的,所以它等待add()完成。 This is all running in Thread 1. If Worker.add should merely adds the work to a list of work, and in the run() method handle its work (executed in its own thread). 这一切都在线程1中运行。如果Worker.add应该只将工作添加到工作列表中,并且在run()方法中处理它的工作(在自己的线程中执行)。

This is a classical Consumer/Producer problem. 这是一个典型的消费者/生产者问题。 (Blocking) Queues might help you. (阻止)队列可能会帮助你。

You need a third class called resource. 您需要一个名为resource的第三个类。 Your threads will communicate through the shared resource. 您的线程将通过共享资源进行通信。 Think producer-consumer Your workers will add to sortedReult. 想想生产者 - 消费者你的工作者会添加到sortedReult。

public class Resource{
  Queue<String> semaphore = new LinkedList<String>();
  Queue<String> sortedResult = new LinkedList<String>();

  public synchronized addStrings(List<String> words){//for reader
    semaphore.addAll(words);
    notify();
  }//

  public synchronized String getString(){//for workers
    while(semaphore.isEmpty())
       try{ wait();}
       catch(InterruptedException e){}
    return semaphore.remove();
  }
}

by the way, that you are calling run() shows you kind of understand the logic. 顺便说一句,你调用run()表明你有点理解逻辑。 But in Java, you must call start() and let start() in turn call run() for you. 但是在Java中,你必须调用start()并让start()依次调用run()。

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

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