同时启动多个线程 [英] Starting multiple thread at the same time

查看:175
本文介绍了同时启动多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图写一些java应用程序。
这个应用程序想要运行的是处理一个文本文件。



但是,输入文本文件很大(超过200mb)
分割200mb为四个拆分文件(每个50mb)



然后,使用四个线程尝试同时处理每个拆分。



所以,我做一个类实现runnable,它有一个文本过程模块。
然后,我使4 obj的(命名worker1〜worker4)runnnable类然后调用:

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

但是,这些线程不是同时运行,而是线性运行。
这意味着,在worker 1线程完成后,worker2线程正在运行。



因此,每个线程只需0.5秒, ,每个花费2秒。 (worker1为0.5s,worker2为0.5s,worker3为0.5s,worker4为0.5s)
如果我可以同时运行4个线程,我预计这个应用程序只需要0.5秒或者小于1秒

解决方案

您需要启动一个线程。所以:

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


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?

解决方案

You need to start a thread. So:

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

这篇关于同时启动多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆