Java: concurrency with Runnable

In this simple tutorial we will see how to process some work in multiple threads using limited pool of x threads. Please note that there is an overhead in using threads.

You could use number of available CPUs as your pool size.



Result:


CPUs 8
thread with value 1 current sum 3
thread with value 2 current sum 3
thread with value 3 current sum 6
thread with value 4 current sum 10
thread with value 5 current sum 15
thread with value 6 current sum 21
thread with value 7 current sum 28
thread with value 8 current sum 36
final sum 120
thread with value 11 current sum 66
thread with value 13 current sum 91
thread with value 15 current sum 120
thread with value 9 current sum 45
thread with value 14 current sum 105
thread with value 12 current sum 78
thread with value 10 current sum 55



As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles