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.
A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.
If you remember, threads in Java start execution from the run() method and stop, when it comes out of the run() method, either normally or due to any exception. You can leverage this property to stop the thread. All you need to do is create a boolean variable like. bExit or bStop.
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.
Here is a simple example:
ThreadTest.java
public class ThreadTest { public static void main(String [] args) { MyThread t1 = new MyThread(0, 3, 300); MyThread t2 = new MyThread(1, 3, 300); MyThread t3 = new MyThread(2, 3, 300); t1.start(); t2.start(); t3.start(); } }
MyThread.java
public class MyThread extends Thread { private int startIdx, nThreads, maxIdx; public MyThread(int s, int n, int m) { this.startIdx = s; this.nThreads = n; this.maxIdx = m; } @Override public void run() { for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads) { System.out.println("[ID " + this.getId() + "] " + i); } } }
And some output:
[ID 9] 1 [ID 10] 2 [ID 8] 0 [ID 10] 5 [ID 9] 4 [ID 10] 8 [ID 8] 3 [ID 10] 11 [ID 10] 14 [ID 10] 17 [ID 10] 20 [ID 10] 23
An explanation - Each MyThread
object 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. So t1
does 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
System.out.println("[ID " + this.getId() + "] " + i); Thread.yield();
And the output:
[ID 8] 0 [ID 9] 1 [ID 10] 2 [ID 8] 3 [ID 9] 4 [ID 8] 6 [ID 10] 5 [ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With