Zum Inhalt springen
L

Das Video kommt von YouTube: erst beim Abspielen verbindet sich die Seite mit YouTube (Google).

Multithreading in Java Explained in 10 Minutes

Coding with John10:01 1,2 Mio. Aufrufe veröffentlicht Auf YouTube

Das Wichtigste aus dem Video

Tipp auf eine Zeit – das Video springt genau dorthin.

Transkriptautomatisch erstellt · 90 Zeilen
Herunterladen
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. create a new java class you can call it whatever you want doesn't matter we'll call it a multi-thread thing now
  9. again it doesn't matter what this is called but it does have to extend thread so now that this class extends thread
  10. 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
  11. in public void run open close parentheses and then open and close curly braces since we're overriding the thread classes run method
  12. here it's good practice to put in an at override annotation here above it so that's
  13. 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
  14. 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
  15. loop four and i equals one i less than or equal to five i plus plus just system dot out dot print
  16. 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
  17. 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
  18. milliseconds we want it to sleep so that can be a thousand thousand milliseconds is one second eclipse is giving us an error
  19. 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
  20. 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
  21. 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
  22. first create an object of that multi-thread thing class that we created call it my thing
  23. equals new multi-thread thing now we have this mything object and you and you might think since we implemented the
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. thing two dot start right after the first my thing now if we run our program we can truly
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. start five threads in this for loop so we can watch that go we have now five threads all counting one through
  40. 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
  41. 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
  42. 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
  43. threadnumber and we'll also create a little class variable here just have it a private and threadnumber and in this constructor
  44. 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
  45. 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
  46. 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
  47. 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
  48. 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
  49. it doesn't in this case thread one happens to be printed first and then three and then two
  50. 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
  51. thing first they're all running at the same time completely independently so there is going to be some slight
  52. 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
  53. doesn't impact any of the other ones all the other ones just keep going business as usual so to demonstrate that let's
  54. 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
  55. 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
  56. can save that go back and run it and we can see that thread number three blows up with a runtime exception after
  57. 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
  58. 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
  59. through five and then immediately run into an exception that won't stop all the other threads from still completing
  60. 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
  61. 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
  62. exception in those threads now i mentioned there were two ways of creating a multi-threadable java class and the first way was
  63. extending the thread class and the other way instead of extending the thread class you can implement the runnable interface
  64. 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
  65. 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
  66. 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
  67. my thread equals new thread and then pass it that object that implements the runnable interface so for us it's my thing and
  68. 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
  69. 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
  70. 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
  71. 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
  72. 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
  73. you extend thread you can't extend any other class java doesn't allow multiple inheritance you can only be
  74. 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
  75. 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
  76. 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
  77. 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
  78. 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
  79. you should know how to use one is mythread.join you can see on the documentation here it says that this method
  80. waits for this thread to die and that really is what it does normally when you start a thread the rest of the program will just continue
  81. on but if for some reason you want your program to stop and wait for that thread to complete you can just call the join
  82. method on that thread and it will stop executing that program until that thread completes so java is making us around this with a try catch so we'll go ahead
  83. and do that so here now since we called join right after we start each thread as the program runs it's going to wait
  84. for that thread to complete before it starts the next one so it kind of defeats the purpose of multi-threading in this particular program but you can
  85. see how it would work if you have one thread that you want to wait for another to complete that's what you would use here
  86. you would use the dot join method another method that's good to know is called is alive that just returns a boolean
  87. true or false for whether the thread is currently still running so for example in our case while each thread is still counting from one to five if we called
  88. is alive on it it would return true but once that thread completes if we called is alive it would return false if you've learned something in this
  89. video please let me know by leaving a like and hit the subscribe button so you don't miss each new java tutorial liking commenting and subscribing is the only
  90. way these videos get out to help more people so i really do appreciate it thanks a lot for watching i'll see you next time

Zum Nachlesen