How to start threads in Java – Illustrated Tutorial

How To Start Threads in Java

01. We are going to use the Thread class for this particular example:  Lets open the Eclipse IDE, in my case I use Spring Tool Suite which is a free Eclipse IDE version.  From the menu select File>New>Java Project…

How to start Java threads 01

02. Give the project a name: ThreadSample1…

How To Start Java Threads 02

03.  Press finish…

How to start a Java thread 03

04. Let us create a package…

How to start a Java thread 04

05. Called the package “usingthreadclass” and press finish…

How to start a Java thread 05

06. Lets create a class in the package, from the menu select File>New>Class…

How to start a Java thread 06

07. Call the class ThreadClassSample, and press finish…

How to start a Java thread 07

08. Add a main method to the class…

How to start a Java thread 08

09. Lets create a Thread class that extends Thread, from the menu select File>New>Class…

How to start a Java thread 09

10. Lets call it ThreadRunnerClass…

How to start a Java thread 10

11. In the ThreadRunnerClass extend the Thread class…

Before

How to start a Java thread 11

12. After

How to start a Java thread 12

13. Now will put some code inside the run method to simulate work that is going to be executed in the separate thread, the simulated work consist of a loop that executes 10 times and prints a message on each execution…

How to start a Java thread 13

14. We need to make this a more realistic example, so we will slow down the execution of our simulated work by adding a sleep method of the Thread Class…

How to start a Java thread 14

15. Sleep method throws an interrupted exception so we need to sorround it with a try/catch.

How to start a Java thread 15

16. In the ThreadClassSample class we declare an instance of ThreadRunnerClass and we run it…

How to start a Java thread 16

17. So far we have only the “main” thread and “r1” thread running, lets do some multithreading by instantiating ThreadRunnerClass multiple times and run the ThreadClassSample…

How to start a Java thread 17

18. Let us add the thread name to the message so that we know which thread printed the specific message…

How to start Java threads 18

19. Now lets run the ThreadClassSample program.

How to start a Java thread 19

20. As you can see this are many threads running concurrently. The order of execution is kind of random because that is controlled by the Thread Scheduler.

 

1 thought on “How to start threads in Java – Illustrated Tutorial”

  1. Hey Rafael, I’ve done a fair amount of Java coding, although it’s more C# now – similar though! This is a great resource for tricky thread programming. I was wondering if the Thread Scheduler handles the dreaded deadlock situation?

    I’ve bookmarked this because I called into short projects in several different languages.

    Best Regards,
    Jim

    Reply

Leave a Comment