Could anyone give an example program that explains Java Threads in a simple way? For example, say I have three threads t1, t2 and t3. I want a code that demonstrates that the threads execute simultaneously, and not sequentially.
Could anyone give an example program that explains Java Threads in a simple way?
Share
Here is a simple example:
ThreadTest.java
MyThread.java
And some output:
An explanation – Each
MyThreadobject tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. Sot1does index 0, 3, 6, 9, etc.Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
And the output:
Now you can see each thread executing, giving up control early, and the next executing.