YoonMin Nam
YoonMin Nam

Reputation: 109

Starting multiple thread at the same time

I have been trying to write some java application. What this application wants to run is processing a text file.

However, that input text file is large, (over 200mb) I tried to split 200mb as four split files (50mb each)

Then, using four threads, tries to process each of split simultaneously.

So, I make a class which implements runnable, and it has a text process module. Then, I make 4 obj of that (named worker1 ~ worker4) runnnable class then call:

worker1.run();
worker2.run();
worker3.run();
worker4.run();

However, these threads are not running simultaneously, but running linearly. This means, after worker 1 thread is finished, then worker2 thread is running.

So, each of them takes just 0.5 sec, but with this linear running, It tooks 2 secs each. (0.5s for worker1 + 0.5s for worker2 + 0.5s for worker3 + 0.5s for worker4) If I can run 4 threads at the same time, I expected that this application takes just about 0.5 sec or less than 1 sec which is faster than 2 secs.

How can I do that?

Upvotes: 0

Views: 3294

Answers (4)

Jean Logeart
Jean Logeart

Reputation: 53819

Reading files on one disk usually does not benefit from multithreading.

Try to improve the way you read and process the file. Use a BufferedReader if you do not already use a buffer.

If you do a lot of processing from what is read, then consider multithreading the processing while keeping one thread dedicating to reading.

To run concurrent tasks, you should use an ExecutorService that you instanciate thanks to Executors. Take some time to read the javadoc.

Upvotes: 1

roger zhan
roger zhan

Reputation: 142

Runnable object is not Thread, you need use Thread to run the Runnable Object, like this:

new Thread(worker1).start();

but i think you may face other problems, so please read the java document.

Upvotes: 1

worker1.run();

calls your run method directly. To start a thread (which calls your run method in the new thread), use:

worker1.start();

(similar for worker2/3/4)

Edit: I thought the workers were Threads, not Runnables. mvieghofer's answer is correct.

Upvotes: 0

mvieghofer
mvieghofer

Reputation: 2896

You need to start a thread. So:

new Thread(worker1).start();
new Thread(worker2).start();
new Thread(worker3).start();
new Thread(worker4).start();

Upvotes: 3

Related Questions