Multithreading in Java Explained in 10 Minutes

964.76k views2303 WordsCopy TextShare
Coding with John
Complete Java course: https://codingwithjohn.thinkific.com/courses/java-for-beginners Multithreadin...
Video Transcript:
in this video we're going to talk about how you can implement multithreading into your java programs so you'll be able to write java programs that do multiple different things at the same time my name is john i'm a lead java software engineer and i love sharing what i've learned in a clear understandable way so if you like this video be sure to subscribe so you don't miss each new video i also have a full java course available in the link down in the description if you're interested multi-threading is the ability to execute multiple different paths of code at the same time so normally in your java programs it's only using one thread but you have the ability to break off into multiple threads and do multiple things at once and i'm going to show you how to do that right now in java there are two main ways of creating a new thread the first way is to have a class extend the thread class that might sound a little complicated but it's really not so to do that right here next to your main class you're just going to want to create a new java class you can call it whatever you want doesn't matter we'll call it a multi-thread thing now again it doesn't matter what this is called but it does have to extend thread so now that this class extends thread the only other thing you have to do in this class to make it multi-threadable is to override the thread classes run method to do that you just have to type in public void run open close parentheses and then open and close curly braces since we're overriding the thread classes run method here it's good practice to put in an at override annotation here above it so that's really all the setup that you need the only thing you have to do now is write whatever code that you want to run in multiple threads inside this run method so let's just do something really simple here like um count up the numbers uh from one to five so we can just do that with a simple for loop four and i equals one i less than or equal to five i plus plus just system dot out dot print line um i and just to make this a little bit more interesting we're going to make it a sleep for one second between each number it prints out that way we can watch it print out each number one at a time to do that we can just do thread dot sleep and we put in the number of milliseconds we want it to sleep so that can be a thousand thousand milliseconds is one second eclipse is giving us an error here because we have to uh surround a thread. sleep with a try catch so we can just have it automatically do that we don't have to do anything special if we run into any exceptions so this empty catch block is just fine so now we have a class that extends thread and we have overridden the thread classes run method so now how do we go about actually kicking off this code in multiple threads to do that let's go back to our main class and first create an object of that multi-thread thing class that we created call it my thing equals new multi-thread thing now we have this mything object and you and you might think since we implemented the run method that we want to actually call my thing dot run now you can do that that'll work it'll run the code that we wrote in that run method but it won't actually do it in a separate thread to actually kick off a new thread you have to instead call my thing dot start so now what will happen here as soon as it gets to this part in the code java will branch off a brand new thread and start running this run method and after it kicks off that new thread and lets it go do its thing it will proceed down the main thread that it was executing here so now we can go ahead and run it and watch it go with just one thread one two three four five and then the program finishes so that's cool and all but the whole point of this is multi-threading so let's go ahead and create a second thread and watch them go at the same time so let's just copy paste that we'll say my thing two and then copy paste that and say my thing two dot start right after the first my thing now if we run our program we can truly see that we have two different threads counting up one to five at exactly the same time as a quick note if we would have called our run method instead let's go ahead and change these both to use run we can see that it's not actually doing multiple threads it's doing the first my things run printing out one through five and then once that's done it finishes and does the second things a counting of one through five it's not doing them both at the same time so remember you have to use the start method if you actually want multiple concurrent threads now if you want more than just like two threads like this you can create a whole bunch of them very easily by doing something like a for loop or and i equals zero less than five let's say we want to try doing five threads at a time i plus plus we can just take this line copy it in here and the start command here get rid of all this we don't need it anymore and now we'll create and start five threads in this for loop so we can watch that go we have now five threads all counting one through five at exactly the same time to make things a little bit more interesting we can kind of assign a number to each thread so we can see which thread is printing which number to do that we can go back over to our multi-thread thing class and actually create a new constructor so just be public multi-thread thing and we'll actually have it taken a parameter of an int and we'll just call it threadnumber and we'll also create a little class variable here just have it a private and threadnumber and in this constructor we'll just assign this. threadnumber to be equal to the threadnumber that's passed in in the method here so now back here in our main class where we're creating this multi-thread thing object we need to pass in a number for the thread number and here we can just use i because we're going through a for loop anyway but what's neat about that is in our run method instead of just printing out i we can print out a which thread it is so like from thread thread number go back and run our program we can now see which thread is printing which number and we get some kind of interesting results so you might assume that because thread 0 was created first that it would get printed out first but it doesn't in this case thread one happens to be printed first and then three and then two what that tells you is that when you break into multiple threads there's absolutely no guarantee which thread is going to be doing its thing first they're all running at the same time completely independently so there is going to be some slight variance in their timing one of the really cool things about multi-threading is that if one of the threads blows up with some kind of exception it doesn't impact any of the other ones all the other ones just keep going business as usual so to demonstrate that let's actually um make an exception happen in one of the threads so let's just say here in our run method we could just say if thread number equals um three we're just going to flat out throw a new runtime exception so of course this will make thread number three blow up so we can save that go back and run it and we can see that thread number three blows up with a runtime exception after it prints the number one but all the other threads go ahead and continue printing out all their numbers let's go ahead and get rid of that bit of craziness but that even applies to our main thread if in here we go ahead and start all these other threads counting one through five and then immediately run into an exception that won't stop all the other threads from still completing so if here we say throw new runtime exception run our program and we can see that even though we run into a runtime exception in the main thread in our main method all of those other threads that we kicked off continue to run completely independently because there was no exception in those threads now i mentioned there were two ways of creating a multi-threadable java class and the first way was extending the thread class and the other way instead of extending the thread class you can implement the runnable interface what's nice about that is that when you implement the runnable interface the only thing you have to do is have your own implementation of the run method which is the same as if you extend thread so there's really nothing else you have to change about this class but back here in our main method we can't just call start anymore because we don't extend threads so there's a small extra step all i have to do is say thread my thread equals new thread and then pass it that object that implements the runnable interface so for us it's my thing and then instead of my thing.
start we'll say my thread. start we'll also get rid of this silly exception but really that's the only other thing that changes you can go ahead and run your program and all of your threads will operate at the same time exactly as they did before so you're probably wondering you know which is better which one should i do you can either extend the thread class like we did first or implement the runnable interface like we have here on one hand if you extend the thread class you get rid of the need to have this little extra line where you're creating a thread but on the other hand i think there is a major advantage to implementing the runnable interface instead of extending thread so the problem here is that if you extend thread you can't extend any other class java doesn't allow multiple inheritance you can only be a subclass of one class and if you are a subclass of thread by extending thread you can't be a subclass of any other class and you're just kind of stuck if you implement runnable you can still have it extend any other class that you might feel like extending that makes sense for your code and also java doesn't limit the number of interfaces you can implement so you can implement another interface here too so although using implements runnable kind of gives you that extra step of having to create a new thread here before you can use it it does give you a whole lot of flexibility to be able to have your multi-threading class extend any other class you might want there are also a few really useful methods on thread that you should know how to use one is mythread.
Copyright © 2024. Made with ♥ in London by YTScribe.com