开发者

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, ho开发者_运维问答w 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. 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?

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. 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). Threading is quite a big subject, but by using well-defined idioms from the Concurrent package it can become a bit more bearable.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜