CodeGym /Courses /Java Core /Creating and starting new threads

Creating and starting new threads

Java Core
Level 6 , Lesson 2
Available

"Hello, Amigo! Ellie told you about threads, and I'm going to tell you how you work with them. To create a new thread, you need to:"

1) Create a Thread object

2) Pass it the method you want to run

3) Call the start method on the created Thread object.

Consider this example:

Code Description
class Printer implements Runnable
{
public void run()
{
System.out.println("I’m printer");
}
}
Class that implements the Runnable interface.
public static void main(String[] args)
{
Printer printer = new Printer();
Thread childThread = new Thread(printer);
childThread.start();
}
1 Create an instance of the Printer class, which implements the run method.
2 Create a new Thread object. We pass the constructor the printer object, whose run() method needs to be invoked.
3 Start the new thread by calling the start() method.

Small Java programs usually consist of one thread called the «main thread». But programs more often launch additional threads, which are called «child threads». The main thread runs the main method and ends. The run method of the Runnable is the analogous method for child threads.

"Ah, lots of threads means lots of main methods."

Creating and starting new threads - 1

To tell a Thread object which specific method it should start, we need to somehow pass a method to it. In Java, this is done using the Runnable interface. This interface contains a single abstract method: void run(). The Thread class has a Thread(Runnable Runnable) constructor. You can pass in any object that implements the Runnable interface.

Your class must inherit Runnable and override its run method. Invoking this method is what starts the new thread. You can write whatever you want in the run method.

Code Description
class Printer implements Runnable
{
private String name;
public Printer(String name)
{
this.name = name;
}
public void run()
{
System.out.println("I’m " + this.name);
}
}
Class that implements the Runnable interface.
public static void main(String[] args)
{
Printer printer1 = new Printer("Nick");
Thread thread1 = new Thread(printer1);
thread1.start();

Printer printer2 = new Printer("Jack");
Thread thread2 = new Thread(printer2);
thread2.start();
}
Create two threads, each of which will be based on its own Printer object.
public static void main(String[] args)
{
Printer printer = new Printer("Natasha");

Thread thread1 = new Thread(printer);
thread1.start();

Thread thread2 = new Thread(printer);
thread2.start();

Thread thread3 = new Thread(printer);
thread3.start();
}
Create three threads based on a single Printer object.

What's more, you can combine this all into one class. The Thread class inherits the Runnable interface, so you only need to override its run method:

Another way to create a new thread
class Printer extends Thread
{
private String name;
public Printer(String name)
{
this.name = name;
}
public void run()
{
System.out.println("I’m " + this.name);
}
}
Inherit the Thread class, which implements the Runnable interface, and then override the run method.
public static void main(String[] args)
{
Printer printer = new Printer("Jack");
printer.start();

Printer printer2 = new Printer("Jack");
printer2.start();

}
Create two threads, each of which will be based on its own Printer object.

"This is a more elegant solution."

"Yes, but it has its shortcomings:"

1) You may need to start several threads based on a single object, as in the example with Natasha.

2) If you inherit from the Thread class, you can't add another parent class to your class.

3) If your class has a parent class, you can't add Thread as a second parent class.

"In other words, after the start method is called, each of the threads starts executing the run method of the object passed to the constructor?"

"Yes. If nothing is passed to the constructor, then Thread just executes its internal run method."

"But why don't we just call the method like this?"

Code
public static void main(String[] args)
{
 Printer printer1 = new Printer("Nick");
 printer1.run();
}

"When the main thread reaches the run method, its "little robot" simply goes inside and executes all the commands inside it. Only after they are executed will it return to the main method and continue the execute further commands. Thus, no second "little robot" will be created. All the work will be performed sequentially, not in parallel (simultaneously)."

"I see. Can you call some other method, something other than run?"

"No. It's all tied to the Runnable interface, which only "knows" about one of its methods: run()."

Comments (17)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Emmelie Level 26, Göteborg, Sweden
5 June 2024
So the start() method is inside the Thread class, and this class is implementing the Runnable interface? When the start() method is called, the run() method gets executed? I think the text could have been clearer about that.
Anonymous #11016365 Level 39, Detroit, United States
3 September 2022
This article mentions that in order to create a new thread on must follow these steps: 1) Create a Thread object 2) Pass it the method you want to run 3) Call the start method on the created Thread object. However, in the following example that is not entirely what is going on.

public static void main(String[] args)
{
Printer printer = new Printer();
Thread childThread = new Thread(printer);
childThread.start();
}
Instead what is happening here is an instance of the printer class (which implements Runnable) is being passed to the Thread constructor. So when the author says "Pass it the method you want to run", this is incorrect because that is not what is happening here. If my understanding is incorrect please correct me, but this is confusing to read because the author is saying one thing, but doing something else in the examples.
Andrei Level 41
11 December 2020
For me, one of the last paragraphs is not quite clear. Can somebody explain it, please? "When the main thread reaches the run method, its "little robot" simply goes inside and executes all the commands inside it. Only after they are executed will it return to the main method and continue the execute further commands. Thus, no second "little robot" will be created. All the work will be performed sequentially, not in parallel (simultaneously)."
Andrei Level 41
15 December 2020
Nevermind, I got it eventually. It's pretty straightforward, when you start a new thread the program goes into the overriden run() method and executes whatever is in there and when it finishes it gets out and carries on whatever is next.
Gellert Varga Level 23, Szekesfehervar, Hungary
29 March 2021
I do not think so. When you start a new thread with the start() method, it will automatically start running the object's run() method. And the execution will bounce there and back between the main thread and the new thread. They run in parallel. If you call just the run() method and not the start() method, the new thread will not start. In this case, only the main thread will run in traditional way = no "robot" will work in main() method until main thread ends with run() method. (This is how I interpreted these two lectures.)
Jonaskinny Level 25, Redondo Beach, United States
10 March 2022
I agree
Lawson Level 29, Lagos, Nigeria
30 August 2020
To make a thread, make a Thread
Daniel Walbolt Level 22, Waterville, United States
4 July 2020
Even the biggest enterprise level applications will only use 2 to 4 Threads as this is standard for most computers to have. Game Development is where multi-threading takes a huge role; because games use very complex calculations and rendering, one thread can do the user interface, character movement, and chunk loading while other threads work on enemy pathfinding, and shadows. If someone ever tried running a complex game on a single Thread, you would get hitches or frame skips every time the Game Engine went through the "drawShadows()" methods, just because it takes awhile to run.
Vitalina Level 20, Poland
16 December 2020
It's very interesting information.!🙂 Are you fond of games?
Kristians Level 32, Riga, Latvia Expert
8 February 2021
great insight, thanks
Hoist Level 2, San Diego, United States
13 November 2022
Yes -- shifted from salesforce to learning gaming engines w/ C# and C++ ... learning some unreal + unity
Manish Sinha Level 26, london, United Kingdom
14 April 2020
this is the interesting one among all others as I was completely unaware of threads aka robots.. thank you codegym team again.
Seb Level 41, Crefeld, Germany
3 February 2020
Alrighty, depending on the specific situation either the Runnable interface is implemented or the Thread class is inherited. Very nice first description. Thanks and cheers.
Rakesh Kumar Level 16, Gambat, Pakistan
24 July 2019
it says threads.this cannot be refrenced from a static block
Fa Yu Level 16, Tashkent, Uzbekistan
10 July 2019
is it some kind of thing that could be useful in AI?
Ewerton Level 30, Belo Horizonte, Brasil
2 July 2019
Sounds like something you will only see in big projects