Multithreading in Java – Part 1 (Introducing Multithreading in Java)
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703564773_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Multithreading in Java – Part 1 (Introducing Multithreading in Java)
Hi there in the next series of lectures we’re gonna get into a new topic in Java known as multi-threading so to better understand this concept I’m just going to give you a little bit of background information before we get into the details when you’re using your computer you often have multiple applications
Running and they’re usually running at the same time right some of these applications you may be aware of and others may be behind the scenes right let’s consider a typical example of a user browsing the internet using you know the Chrome or Firefox browser while the user is browsing the Internet
They may also have a music player running both the music player and the internet browser or applications running at the same time behind the scenes there may also be a virus protection software scanning your computer for malware these three applications can also be referred to as processes three independent
Processes running at the same time now there are usually a lot more processes running on your computer behind the scenes but these three let’s just consider these three in this example now within each process there could also be lighter-weight child processes let’s take an example of the internet browser applications such
As Chrome or Firefox a user could have multiple chrome or firefox internet tabs open right one of the tabs could be playing music from YouTube and the other tab may be refreshing their Gmail inbox and you know another third tab may be refreshing a Facebook feed all of these
Browser tabs work simultaneously within the parent process okay so these these you can consider these child processes the different tabs that you have open now in computer science these child processes are also referred to as threads okay the various programs that we’ve been writing in this course
So far right these Java programs they’ve so far only been single thread programs in other words at any given point in time there was only one thread or one task really and that thread was known as the main thread now I’ll go over the main thread in just a minute
But within this main thread instructions were executing sequentially one by one and what were these instructions these were those lines of code that you’ve been writing when one line of code would complete and running the next line of code would execute and so on this is a single threaded execution at any given
Point in time only a single line of code was executing but you can also write multi-threaded programs and you could probably guess what that means this typically means that two or more lines of code can run at the same time for example you could write a java application that is downloading files
From the internet and performing statistical calculations on that data and you know loading a summary file into a database you know these are different tasks and each one of these tasks can be running on their own thread of execution okay and all of them could be running at
The same time one thread can be responsible for only downloading the files from the Internet another thread could be you know creating those those files to load in the database and the third thread could be responsible for reading data and performing calculations all three of these flows of the program these tasks
These three tasks could be happening at the same time and which would mean that multiple lines of code are being run simultaneously all right that’s the core of multi-threaded programming multiple lines of code running at the same time right now writing multi-threaded programs can be a challenging feat and
Often takes many iterations of refracting the code over time and you know to build a stable application and the complexity here arises when threads need to communicate with each other you know deadlock situations can occur where a thread a is waiting for thread B to come however thread B is actually waiting on
Thread a to complete this will all make sense when we go into the details of some of these messy scenarios and I’ll go over that in great detail in this in the remaining lectures but for now let’s go over how to start a thread in Java so
Here we are in Eclipse I’ve created a project called learning threading so you can go ahead and do the same and I have a package here called comm dot job-ready dot threading okay and that’s just a naming convention that we spoke about earlier where we have this comm followed
By your company followed by the kind of thing that this package contains and we’re going to be learning threading so that’s what I called it and in here we have a class called application so let me show you how to create your first thread in a java program I’m going to
Define the public static void main method here and inside of this method I’ll have a simple print line statement that just says you know hello there it doesn’t really matter what we have there but now if I hit the play button we would have started a thread believe or
Not so that’s it play there you go it says hello there we actually executed a thread and that was the main thread main method starts everything and what it is is it starts a thread now within this thread you know so far in this course you’ve been writing all the code inside
Of main and sequentially line by line it was being executed right even if we were involving multiple classes that code was you know being utilized here in this main method because it’s executing line by line meaning at any given point in time we were only having one line being
Executed right one after the other but how do we get two lines to run at the same time that’s where multi-threading comes in right so at this point we’re single threaded but now let’s make this multi-threaded outside of this class called application I’m going to define
Within the same file I’m going to define another class let’s call it task and that’s what I want you to start thinking about is this task driven mindset especially when it comes to writing threaded programs because the thread is essentially a task I want you to think
Of that as a task in and and the task has steps that need to be executed so I created this class called task and it’s going to extend the thread class okay in this this class has been around since Java one right from the early days of Java Java was multi-threaded and and
That’s one of the competitive advantages Java had right from the start so if you go to the definition of this thread class I’m going to control click it notice that this is a class that implements runnable if we go into the runnable interface it has this method
Called run and it’s an abstract method so to create a thread we need to override this run method so since this thread class is implementing this runnable interface it must have implemented a version of the run method within the body of this class right so
Let’s look for that I just want to show you if you type in run and then you put parentheses and it’s a void method so it doesn’t return anything I’m just gonna put that as the signature unless search for that in this class and there we go
Notice that this is that method it’s being over overridden in this thread class well we’re actually also going to override it so this new class that we defined called task is actually going to have its version of run and that’s the guy that’s going to be executed on a
Separate thread so let’s create that method I’m going to do public void run and in this method all I want to do is just create a loop to print some data so it’s just going to be a for loop and we’re gonna initiate the variable I for
Iteration we initialize it to zero and then I is less than 1,000 and I plus plus and in this loop I’m just going to print out the value of I okay so I’m just gonna write the the word number with a colon and just append the value
Of I to that and now when I run this program what do you think is going to happen right you haven’t done anything really we’re defining this this structure of what a threat is we called it a task and we gave it the instructions but we
Haven’t kicked it off yet this is still a single-threaded program if I hit play this is still a single-threaded program only the main thread gets one so let’s create an instance of task which is essentially a thread right it’s extending the thread class it is a
Thread that’s what I want that’s how I want you to think about it so let’s create an instance of task and the object name is task runner there’s new task and even to this point this is still a single threaded program right what we have to do is we need to
You might be thinking that we need to invoke the run method but that’s not what you do you actually have to invoke a method called start right here and you can see that this causes this thread to begin execution so this is the guy that
We want to call and what that’s going to essentially do is invoke this run method in a separate thread so if I run the program the way it is right now it’s going to print hello there first and then it’s gonna print the numbers from
Zero thousand or 0 to 999 so let’s hit play and these are the numbers that scroll up all the way to the top notice it printed hello there now let me prove to you how this is a multi-threaded program if we move this code above that print statement so with the previous
Knowledge in the course you know we’ve only been working with single threaded programs prior to this lecture right so you were aware that until one line of code is isn’t complete it doesn’t move to the next line right we wait till that line is complete then sequentially it moves to the next line
And so on that’s a sequential single-threaded program that’s what you’ve been working with but in a multi-threaded program if a new thread is spawned it doesn’t wait for that code to complete it just says ok go ahead and execute this code and it could take you
An hour I don’t care I’m moving on to the next line and that’s exactly what’s going on here let me prove it to you if I hit play notice that towards the end of those numbers we don’t see that print statement where is it let’s go all the way to the top it
Actually executed that first and the reason behind this is because when it when the interpreter got to the line where it says task runner dot start it didn’t wait until that line is completed right it didn’t wait for all those numbers you know from 0 to 999 to be
Printed until it moved to next line it just said haste a thread start yourself and that thread was started and the interpreter continued to move on to the next line to bigger and better things so the reason for why the word hello there was printed first is because it takes
Time for a thread to fire up okay what to get spawned so to speak so when the thread was spawning before it actually kicked off the words hello there were printed but if we had other things down you know printing you know much later on in the code they could have appeared
While those numbers were actually bringing being printed you know it could have printed something you know between the numbers 55 and 100 or between the numbers 350 or 400 it could have printed other things if we had more code because a thread is running and it’s going to
Continue to run until it’s completed and you know that’s one flow whereas another flow of code may also be running on a different thread so that’s the whole idea behind multi-threading and this is gonna make much more sense as we look at more examples again just like before other parts of this course
I don’t shy away from repeating myself so I’m just going to go over this once again with you because it’s such an important concept so this is a multi-threaded program because once this task runner was started it was kicked off the Java interpreter didn’t just wait here
It didn’t wait for this to complete it moved on to bigger and better things it started this thread and this thread is going to do what it needs to do but the interpreter is moving on to the next line and then it printed out this so it
Kicked off this thread moved on to bigger and better things and we are here now you might be wondering what if we want to run through this loop again could we do a task runner dot start again well think about it we told Java to go on and kick off a
Thread and it does this by using the start method and the way it has access to that is through this instance variable called task runner so the thread has been spawned and kicked off but if we try to do this again using the same instance it will actually fail it’s
Going to give a special exception and that’s called illegal thread state exception if I hit play again notice that you saw a little bit of red there let’s go to the top and saying you know exception in thread main so always remember it’s it’s never illegal to
Start a thread more than once okay in particular a thread may not be restarted once it has completed execution always remember that so the solution to this if you want this to you know go through this loop again for whatever reason and you want to do it in
A different thread the way to do that is to use this task class to create a new instance and then kick off that instance alright so we do tasks and I’ll call it task runner two is equal to new task and then use this guy to start the thread again
Well not again we’re starting a new thread so just like in regular object-orientation a class is a blueprint right it designed for you know that contains instructions and methods and so on so we’re just using the same blueprint of what we consider a task which is a thread and
We’re just utilizing that blueprint to kick off a new thread so the instructions in this task you know what to do those steps are the same as this task but they’re gonna run separately in two different threads so let’s hit play and notice that now we don’t have we
Shouldn’t have that error another thing I want you to notice is the way these numbers are printed out alright let’s go through this for a second the first number printed out is zero and then it moves on to one two three and whoops there’s another zero number four and
There we go we got number one again number five and there we go we got number two again number six and there we go we got number three again so notice that the results of what’s being printed here is coming from two individual threads okay so this this particular
Code is being run on two separate threads okay one of the threads has been started for at you know at this line and the next thread ends up starting here so that’s why you see those numbers repeating they all go from 0 up to 999 and that’s what you’re going to see all
The way to the bottom here is 999 and you’ll find repeating numbers as you scroll through this so hopefully threading is starting to make some sense we’re gonna get into much more detail and we’re gonna look at all kinds of scenarios that can take place in threading so just a quick review before
Wrapping up this lecture I want you to think of a thread as a flow through your program okay so the first thread that gets kicked off is the main thread so it starts off here the JVM kicks off the starter main thread and what that does
Is it looks for this main method which is the entry point of your application and it executes whatever is in here so when it enters into here it sees this line and says oh we need to start a thread so it starts off a flow so to
Speak all right and that flow is right here so it just kicks that off but doesn’t stop there it continues on and it sees this print line statement it prints that and then you know sees another thread that needs to be started so it kicks off this thread as well and
Then moves on and finishes the main thread here while the other two threads are still running okay until these don’t complete they’re gonna continue to run and up to this point the main thread has pretty much been completed but these two other threads are still going on ok so
That’s how I want you to think about multi-threading is threat is basically a flow through your program this first starting of a thread right this was the kickoff of this flow and then the second kicking off of a thread is starting a new flow which is
Also going to do the same thing and that is why we see some of these numbers repeating so there’s a lot more to go over when it comes to threading we’re going to go into all different kinds of scenarios but for this lesson I’m going to wrap it up here thanks for watching
I’ll see you in the next lecture
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
5:24 general kenobi
شرحك مفهوم و الفكرة وصلت بشكل سريع، شكرا جزيلا
Awesome tutorial!! Really helpful. A tips would be to get a popfilter or something like that since it feels like ASMR in my ear. Otherwise 10/10
You are like @thenewboston for java! killer explanation! thank you for making this public!
Amazing pedagogic skills and great communicator. Good job!
thank you sir..nice way of explanation .
hey guys I have made an excellent video on Multi-threading, kindly visit to my channel…
Multi-threading in JAVA (Live practical implementations)
https://youtu.be/7-RS16vhXMA
great at explaining
thanks
Love this. Thank you,
17:48 that huge cursor hue
Very pragmatic approach to explain Threads.
Very helpful, thank you very much!!
Thanks.. you have given a very nice and crystal clear explanation.. Keep it up
If only I found out about this guys course earlier. His lifetime subscription is what I pay monthly for my current one and he is a gifted educator and teacher way above my professors.
You've got added to my youtube fav list🙌🏾
I'm a subscriber and have been better prepared for classes because of your tutorials. Thank you. Also, why do you use eclipse over intellij?
nice tutorial