简体   繁体   中英

java thread multithreading

In java, will adding multiple threads to do one task in java help in executing that task faster?

currently the main thread was used in my program, but it was slow. My current measurements were 500 process per second, but the total number of processes were over a billion. How can I make my program runs faster?

In java, will adding multiple threads to do one task in java help in executing that task faster?

It entirely depends on what you're doing. If you're performing tasks on independent pieces of data, with no bottleneck in either retrieving or storing the results, and assuming you're on a machine with more than one processor then yes, using more threads is likely to help.

However, there are various ways it can not help:

  • If you're reading input data from a slow resource, you may be processing it as fast as you can read it anyway
  • If you're writing results to a slow resource, you may be processing it as fast as you can write the results anyway
  • If one task depends on the results of another, you may not be able to get any parallelization
  • If you've only got one CPU core, and the task is already CPU-bound, then adding more threads won't help

In some of these cases threading can help , but not as significantly as if it's just CPU bound and you have plenty of spare cores. You need to work out where your current bottlenecks are.

Note that in the best case you're only going to get a speed-up proportional to the number of cores you've got. So if you've got 16 cores (unlikely but feasible) and perfect parallelization, then if one core can process 500 items per second and you've got a billion items, it's still going to take nearly 35 hours to process everything.

One thing which is almost certain is that your multi-threaded code will be more complicated than you single-threaded code. Try to use high-level abstractions (eg the ones in java.util.concurrent instead of low-level ones (such as java.lang.Thread ) to make things simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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