Java Thread run() method

The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

The run() method can be called using the start() method or by calling the run() method itself. But when you use run() method for calling itself, it creates problems.

Return

Example 1: call the run() method using the start() method

Test it Now

Output:

Thread is running...

Example 2: call the run() method using the run() method itself

Test it Now

Output:

running...

In this case, it goes to the current call stack rather than at the beginning of a new call stack.

Example 3: call the run() method more than one time

Test it Now

Output:

1
2
3
4
5
1
2
3
4
5

In the above Example 3, there is no content switching because here t1 and t2 is treated as a normal object not thread object.






Latest Courses