Java multithreading 🧶

Поделиться
HTML-код
  • Опубликовано: 2 окт 2024

Комментарии • 156

  • @BroCodez
    @BroCodez  4 года назад +84

    //*******************************************************
    public class Main{

    public static void main(String[] args) throws InterruptedException{
    // Create a subclass of Thread
    MyThread thread1 = new MyThread();

    //or

    //implement Runnable interface and pass instance as an argument to Thread()
    MyRunnable runnable1 = new MyRunnable();
    Thread thread2 = new Thread(runnable1);


    //thread1.setDaemon(true);
    //thread2.setDaemon(true);

    thread1.start();
    //thread1.join(); //calling thread (ex.main) waits until the specified thread dies or for x milliseconds
    thread2.start();

    //System.out.println(1/0);
    }
    }
    //*******************************************************
    public class MyThread extends Thread{
    @Override
    public void run() {

    for(int i =10;i>0;i--) {
    System.out.println("Thread #1 : "+i);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("Thread #1 is finished :)");
    }
    }
    //*******************************************************
    public class MyRunnable implements Runnable{
    @Override
    public void run() {

    for(int i =0;i

    • @Sorjen108
      @Sorjen108 2 года назад

      Hello
      I have a question
      How would you create a multi-threaded program with 2 FOR loops, and change the priority of the loops to make the second loop terminate before the first loop?
      I have tried to use the set priority but to avail, the first FOR loop always gets executed first

    • @jojovstojo
      @jojovstojo Год назад +1

      public class Main{

      public static void main(String[] args) throws InterruptedException{
      //1st Way of creating a Thread :: Create a subclass of Thread class
      MyThread thread1 = new MyThread();

      //or

      //2nd Way of creating a Thread :: Implement Runnable interface and pass instance as an argument to Thread()
      MyRunnable runnable1 = new MyRunnable();
      Thread thread2 = new Thread(runnable1);


      thread1.setDaemon(true);
      thread2.setDaemon(true);

      //Normally, when thread1 & thread2 are not daemon threads -- in that case, even if an exception occurs in the 'main' thread, the other two threads will continue to run (& complete) without any interruption. But, if we make the threads - thread1 & thread2 - into daemon threads - then in that case there remains only one primary/user thread i.e 'main' thread. An then, if any exception occurs in our one and only user/primary thread i.e main thread, then the compiler does not care to complete the execution of daemon threads (threads1 & thread2) and the whole program immediately stops.

      thread1.start();
      thread1.join(); //this line of code makes the 'main' thread wait/pause untill the thread1 completes its excecution. And once thread1 completes its execution, the main thread continues again -- i.e starts threads2.
      // thread1.join(3000); //this line of code makes the 'main' thread wait/pause for 3000 milliseconds (after starting of thread1) before continuing its execution -- i.e starting threads2.
      thread2.start();

      //An important point to note here is that even if there occurs an exception during execution of one of the threads, the other thread/threads continue to run without any problem.

      System.out.println(1/0); //This will cause an exception in 'main' thread but the threads 'thread1' and 'thread2' will continue to run without any interruption. But, if threads - thread1 & thread2 - are made into daemon threads, then in that case there remains only one primary/user thread i.e 'main' thread. Then, as soon as the exception occurs in the main thread (1/0), the compiler does not care to complete the execution of daemon threads (threads1 & thread2) and the whole program immediately stops.
      }
      }
      **********************************************************************************************************************
      public class MyThread extends Thread{
      @Override
      public void run() { //When we start an instance of this thread, the code inside run() function executes. run() is a function of Thread class.

      for(int i =10;i>0;i--) {
      System.out.println("Thread #1 : "+i);
      try {
      Thread.sleep(1000);
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      System.out.println("Thread #1 is finished :)");
      }
      }
      *********************************************************************************************************************
      public class MyRunnable implements Runnable{
      @Override
      public void run() {

      for(int i =0;i

    • @joyceasante8292
      @joyceasante8292 Год назад

      Practicing...
      1st Method(Creating a subclass of the the tread class)
      public class Main
      {
      public static void main(String[] args) {
      MyThread thread1 = new MyThread();
      }
      }
      ***************************************
      public class MyThread extends Thread{
      @Override
      public void run(){
      for(int i=10; i>0; i--){
      System.out.println("First thread : "+i);
      try{
      Thread.sleep(2000);
      } catch(InterruptedException e) {
      e.printStackTrace();
      }
      }
      System.out.println("First thread is completed.");
      }
      }
      _____________________________________________
      2nd Method(Creating a class that implements the runnable interface)
      public class Main
      {
      public static void main(String[] args) {
      MyThread thread1 = new MyThread();
      MyRunnable runnable1 = new MyRunnable();
      Thread thread2 = new Thread(runnable1);

      }
      }
      ****************
      public class MyThread extends Thread{
      @Override
      public void run(){
      for(int i=10; i>0; i--){
      System.out.println("First thread : "+i);
      try{
      Thread.sleep(2000);
      } catch(InterruptedException e) {
      e.printStackTrace();
      }
      }
      System.out.println("First thread is completed.");
      }
      }
      *********************
      public class MyRunnable implements Runnable{
      @Override
      public void run(){

      }
      }
      ______________________
      Successfully Multithreading
      public class Main
      {
      public static void main(String[] args) {
      MyThread thread1 = new MyThread();
      MyRunnable runnable1 = new MyRunnable();
      Thread thread2 = new Thread(runnable1);
      thread1.start();
      thread2.start();
      }
      }
      *******************
      public class MyThread extends Thread{
      @Override
      public void run(){
      for(int i=10; i>0; i--){
      System.out.println("First thread : "+i);
      try{
      Thread.sleep(2000);
      } catch(InterruptedException e) {
      e.printStackTrace();
      }
      }
      System.out.println("First thread is completed.");
      }
      }
      **************************
      public class MyRunnable implements Runnable
      {
      @Override public void run ()
      {
      for (int i = 0; i < 10; i++)
      {
      System.out.println ("Second thread : " + i);
      try
      {
      Thread.sleep (2000);
      } catch (InterruptedException e)
      {
      e.printStackTrace ();
      }
      }
      System.out.println("Second thread is completed.");
      }
      }
      ___________________________________
      Final Code
      public class Main
      {
      public static void main(String[] args) throws InterruptedException {
      MyThread thread1 = new MyThread();
      MyRunnable runnable1 = new MyRunnable();
      Thread thread2 = new Thread(runnable1);
      //thread1.setDaemon(true);
      //thread2.setDaemon(true);
      thread1.start();
      //thread1.join(5000);
      thread2.start();

      System.out.println(2/0);
      }
      }
      ******************************
      public class MyThread extends Thread{
      @Override
      public void run(){
      for(int i=10; i>0; i--){
      System.out.println("First thread : "+i);
      try{
      Thread.sleep(2000);
      } catch(InterruptedException e) {
      e.printStackTrace();
      }
      }
      System.out.println("First thread is completed.");
      }
      }
      **********************************
      public class MyRunnable implements Runnable
      {
      @Override public void run ()
      {
      for (int i = 0; i < 10; i++)
      {
      System.out.println ("Second thread : " + i);
      try
      {
      Thread.sleep (2000);
      } catch (InterruptedException e)
      {
      e.printStackTrace ();
      }
      }
      System.out.println("Second thread is completed.");
      }
      }

  • @wanke9837
    @wanke9837 3 года назад +44

    You are absolutely the best teacher for me. I appreciate your teaching methodology and Thanks for everything you put into this course.

  • @Cipher6i8
    @Cipher6i8 2 года назад +1

    Me: Starts learning about exception handling/threading in Java
    RUclips algorithm: Recommends the bro's videos on both custom exceptions and multi threading
    God bless you, bro.

  • @joelmarkjmj
    @joelmarkjmj Год назад +2

    You are my Favourite Java Professor forever

  • @IIITL-CSAI-2023-PC-0
    @IIITL-CSAI-2023-PC-0 4 месяца назад

    Buddy there is no one better than you , when it comes to helping in sem exams ❤

  • @UninspiredFilm5
    @UninspiredFilm5 3 месяца назад

    Spent the whole day trying to make a program work with multiple threads in a method that made no sense, started fresh and this video made it work just right!

  • @darklegend7981
    @darklegend7981 11 месяцев назад +1

    An Hour worth spent learning !Thanks Bro

  • @Mr.Legend_9
    @Mr.Legend_9 2 года назад

    Thanks bro,Ive learned a lot from you...when i first see your videos i dont know anything regarding coding but now i have made my own apps.I came again because i forgot threading basics and my new app really needs it.Keep it up,I Wish you have a happy life.

  • @levi25902
    @levi25902 Год назад

    Threads seemed very hard at campus, your video helped me understand it much better. Thank you for this amazing Video

  • @comic-typ5919
    @comic-typ5919 2 года назад

    You are really talented in teaching others, awesome.

  • @ВолодимирПасічник-ъ8щ

    This is the best video about multithreadind in java!

  • @hgatl
    @hgatl 3 года назад +37

    This is definitely the best description of many videos that i have watched, super

  • @stevancosovic4706
    @stevancosovic4706 3 года назад +1

    Thank you bro! Best programming teacher on youtube

  • @AEINTech
    @AEINTech 3 года назад +10

    We want a video about Threads synchronization and scheduling please. By the way, the video is grate : )

  • @adrian_vsk7203
    @adrian_vsk7203 3 года назад +34

    I tried to learn multithreading on a Udemy course and it seemed super complicated and difficult. This video made it so much simpler and provides really clear examples. Thanks so much Bro! Keep up the great work!

    • @ban_droid
      @ban_droid 3 года назад +5

      Sorry for your money that have been lost to pay that udemy course, lol 😂 i'm glad i'm checking every tutorial on youtube first if its exist for free 😂

    • @Lilyofc
      @Lilyofc 9 месяцев назад +1

      Screw them

  • @hrishikeshmk6243
    @hrishikeshmk6243 9 месяцев назад

    Thanks for all the informative content you've got here bro

  • @azamatdev
    @azamatdev 5 месяцев назад

    Yeah thank you so much i understand so much than i learnt payed one course. ❤

  • @treebit
    @treebit 4 года назад +7

    Hey, Bro, nice job! I watch ur tutorials not even being english speaker and learn a lot! Also do u plan to record JavaScript course? This would be awesome!
    PS sorry for cringy english

    • @BroCodez
      @BroCodez  4 года назад +12

      Your English is good. I understood. Yeah I'm hopefully going to add more Python and Javascript videos in the next few weeks. I would like to bring this Java playlist to 100 videos first. Shouldn't take too long.

  • @kareem1737
    @kareem1737 2 года назад

    Excellent explanation on both threading and multithreading. Thank you!

  • @bosssmith9507
    @bosssmith9507 2 года назад

    Thanks, man this helped with my object-oriented programming class :]

  • @fokas360
    @fokas360 Год назад

    // Your method of teaching is incredible💢[14.06.23]

  • @Monsta1291
    @Monsta1291 2 года назад

    amazing

  • @sean-qo4vc
    @sean-qo4vc 2 года назад

    Good job my guy Skuks(thanks)

  • @eugenezuev7349
    @eugenezuev7349 3 месяца назад

    well done, Teacher

  • @percivalgebashe4376
    @percivalgebashe4376 Год назад

    Nice

  • @alokendughosh7013
    @alokendughosh7013 Год назад

    Subscribed!!
    Keep going bro!!

  • @marwanhussam1299
    @marwanhussam1299 Месяц назад

    good video

  • @nitwaalebhaiya
    @nitwaalebhaiya 2 года назад

    Excellent Explanation.

  • @thedeveloper643
    @thedeveloper643 3 года назад +7

    you're helping me way more than this super thick book that i bought a couple days ago
    the book is probably good to someone else but it explains the same concepts in a complicated way with all the fancy words
    but you make it easier to understand showing simple examples
    it's ironic that it's easier for me to understand something in language that's not my mother tongue
    thank you for great videos! liked and subscribed
    love from south korea!

    • @adityarajsrivastava6580
      @adityarajsrivastava6580 3 года назад

      It is not strange for Hindi is my mother tongue but he gives various hilarious examples which make it easier to learn coding.

  • @Skillet367
    @Skillet367 3 года назад

    Good job man, thanks for the great work.

  • @noahhuffman519
    @noahhuffman519 2 года назад

    So Helpful

  • @-Corvo_Attano
    @-Corvo_Attano Год назад

    Bro Code is a gem :)
    Thank you *BRO*

  • @shibildas
    @shibildas Год назад

    wow. just... wow

  • @usmankabeer6776
    @usmankabeer6776 3 года назад

    Very Helpful VIdeo.

  • @imnithyn4447
    @imnithyn4447 2 года назад

    Dude👌

  • @oguzhantopaloglu9442
    @oguzhantopaloglu9442 3 года назад +2

    amazing!!!

  • @pranjalbajpai9956
    @pranjalbajpai9956 3 года назад

    You are awesome!

  • @РаильРавилов-т9п

    Cool!!

  • @redpepper74
    @redpepper74 8 месяцев назад +1

    There's an easier way to make threads! Runnable is a @FunctionalInterface, which means that you can replace your custom Runnable with a function that takes no arguments and returns nothing. It's much nicer:
    Thread thread1 = new Thread(MyClass::myProcedure);
    Or you can write it as a lambda expression if you prefer this syntax:
    Thread thread2 = new Thread(() -> myProcedure());

  • @emgm6207
    @emgm6207 2 года назад

    You are the best Bro!

  • @DUYNGUYEN-ui9uz
    @DUYNGUYEN-ui9uz Год назад +1

    Could you explain why we should not use inner class when creating thread? For example, I would write:
    Thread thread1 = new Thread(){
    @Override
    public void run()
    {
    //do something
    }
    }
    Thank you!

    • @rionhoxha123gmail
      @rionhoxha123gmail 9 месяцев назад +1

      Using an anonymous inner class directly inside the Thread constructor may lead to less clean and less encapsulated code. It mixes the thread logic with the class definition.
      Separating the thread logic into a separate class or implementing Runnable allows for better encapsulation and cleaner code organization.

  • @superraegun2649
    @superraegun2649 Год назад +1

    wouldn't it be better to name your threads by passing an int into the class and then printing that int, that way you could have as many as you wanted and each would get a different name?

  • @_sf_editz1870
    @_sf_editz1870 2 года назад

    Sensei 😁

  • @stelioskapsis6993
    @stelioskapsis6993 2 года назад

    lets goooooooooo

  • @Dramox.
    @Dramox. 3 года назад +5

    you're doing a better job explaining than my college professors... What's the point of college if I can just sit at home and watch endless youtube videos and learn more for less

  • @callmesuraj4257
    @callmesuraj4257 3 года назад

    super bro

  • @ecstatic6133
    @ecstatic6133 2 года назад

    Thanks ❣
    Well explained

  • @thugsmf
    @thugsmf 2 года назад +1

    Hey bro code, yeah I'm talking to you...lol.. love your teaching style! very practical examples! very easy to understand! the simplicity! never stop teaching! please. a fellow bro. thank you. ps. smashing that like button on every video

  • @Jan-fw7qz
    @Jan-fw7qz 3 года назад

    You're the best ❣️

  • @Genesis-dj7kw
    @Genesis-dj7kw 2 года назад +3

    I must admit, I used to have no damn clue in class about java. Then I bought a Udemy course, which I found better to understand, yet still confusing at times. And now I stumbled upon your tutorials for Java; straight to the point, simple, yet applicable examples and all I need to pass my exams and actually enjoy coding. thank you so much :D

  • @sadeqsz6076
    @sadeqsz6076 Год назад

    thanks

  • @srinivasan4999
    @srinivasan4999 Год назад

    thanks man

  • @ariefsaferman
    @ariefsaferman 3 года назад

    thanks help me a lot in thread

  • @shayo6251
    @shayo6251 3 года назад +1

    Hmm what if you wanted to create like 500+ threads?

  • @lamias7712
    @lamias7712 2 года назад

    Thanks Bro

  • @yashkapoor5894
    @yashkapoor5894 Год назад +1

    Good job my bro

  • @stormpegasus7360
    @stormpegasus7360 3 года назад +1

    I guess I am not failing java

  • @poruboi5924
    @poruboi5924 Год назад

    This saved me

  • @forspt6334
    @forspt6334 3 года назад

    thanks bro !!!

  • @kenkinyua7036
    @kenkinyua7036 2 года назад

    thanks so much ,,,is there sth i should add before setting a sub thread to daemon it's prompting an error kindly help?

  • @imadeveoper
    @imadeveoper 10 месяцев назад

    thing that confuse me is that we are overriding a method called run. but we don't
    have that method in parent class so what type of override it is????

  • @Jin._.20
    @Jin._.20 Год назад

    can you just do Thread t = new Thread(); and would that be the third way to create a thread? (not extending or implement anything) I've heard that if you craete a thread like this way, you need to use lambda expression to tell the program what that thread does instead of overriding run()... Am I correct?

  • @screenname96
    @screenname96 Год назад

    🙏💙

  • @semilife
    @semilife 7 месяцев назад

    Thanks Bro for your excellent resources.

  • @FaridHasanaliyev
    @FaridHasanaliyev Год назад

    Great thank you for such an enourmous work of creating 155 videos playlsit

  • @xvesderx6759
    @xvesderx6759 5 дней назад

    thanks for your great tutorial

  • @rbdtrades9790
    @rbdtrades9790 Год назад

    Hows it going everybody, it's your bro here

  • @nancydai8778
    @nancydai8778 Год назад

    If I have a zip outputstream which is shared by one thread of reading content-copying to zip outputstream and the other thread of writing zip outputstream to response, how do I ensure they are not blocking each other? 🙏🙏

  • @Makariush
    @Makariush Год назад

    Take my energy Bro, beat the almighty RUclips algorithm.

  • @yuvalmuseri5464
    @yuvalmuseri5464 Год назад

    Sank you very much for da knowledge boi

  • @honoredegg
    @honoredegg 2 года назад

    87th. Thank you, ma Bro Sensei

  • @APDesignFXP
    @APDesignFXP 2 года назад

    just commenting to help u with the algorithm champ

  • @nizarouertani1315
    @nizarouertani1315 3 года назад +1

    i m ur new fan :D

  • @natnael_esk
    @natnael_esk 4 месяца назад

    code family , code bro

  • @deatharw1997
    @deatharw1997 3 года назад

    SUBSCRIBED TO BECOME FELLOW BRO xD

  • @chillfill4866
    @chillfill4866 2 года назад

    How to debug with threads?

  • @RohitKudiya1
    @RohitKudiya1 11 месяцев назад

    What is your name bro

  • @erenyeager4452
    @erenyeager4452 2 года назад

    commenting for the algo.

  • @sharathkumar726
    @sharathkumar726 Год назад

  • @augischadiegils.5109
    @augischadiegils.5109 3 года назад

  • @markus_code
    @markus_code 2 года назад

    Thank You for examples. I think now I can run my code without any sluggish methods. But it's not just that I think also I will change structure and logic of my program. D.amn thank you for opening my eyes.

  • @kristjantoplana2993
    @kristjantoplana2993 6 месяцев назад

    Very good.

  • @MmdRsh
    @MmdRsh Год назад

    u are my hero man

  • @danielmilewski7659
    @danielmilewski7659 2 года назад

    comment for stats

  • @Freddie-uk9wk
    @Freddie-uk9wk 3 месяца назад

    a

  • @TheElliotWeb
    @TheElliotWeb 10 месяцев назад

    Thank you! It's a great explanation of basic multithreading stuff what I found on RUclips.

  • @matteocamarca
    @matteocamarca 8 месяцев назад

    THANKS.

  • @calor6990
    @calor6990 Год назад

    Thank you!

  • @mohamadhoseinbemani
    @mohamadhoseinbemani 9 месяцев назад

    my bro

  • @ysf9423
    @ysf9423 Год назад

    thanks bro

  • @mdalladin7227
    @mdalladin7227 Год назад

    love u bro

  • @korolek6442
    @korolek6442 Год назад

    Thank you for this video! it was really helpful :)

  • @VANTYCSolutions
    @VANTYCSolutions 3 года назад

    Live Saver!

  • @gamingisnotacrime6711
    @gamingisnotacrime6711 Год назад

    Dope🔥

  • @MrLoser-ks2xn
    @MrLoser-ks2xn 2 года назад

    Thanks

  • @AzizbekFattoev
    @AzizbekFattoev 9 месяцев назад

    You are my real BRO who saved my entire semester

  • @dmitriinekhristov8334
    @dmitriinekhristov8334 2 года назад

    Thx bro!

  • @kemann3815
    @kemann3815 2 года назад

    Lovely

  • @skyadav8842
    @skyadav8842 2 года назад

    awesome

  • @pvc97
    @pvc97 2 года назад

    Tks you