Multithreaded programming in Java

Photo by aisvri on Unsplash

Multithreaded programming in Java

Mentoring

While doing multithreaded programming in Java, you would need to have the following concepts really understood and have an idea of what they do:

  1. What is thread synchronization?

  2. Handling interthread communication

  3. Handling thread deadlock

  4. Major thread operations

There are 2 ways on how you can implement multithreading in Java:

  • By extending the Thread class

  • By implementing the Runnable class

Both have their pros and cons so lets dig into it and take a look at how to do it both ways.

1. Extending the Thread class

public class MultithreadingExample extends Thread{

  @Overrid
    public void run(){
      for(int i=1; i<=5; i++){
            System.out.println(i);
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){}
        }
  }
}

//run it like this

public static void main(String[] args) {
    MultithreadingExample multiThreading = new MultithreadingExample();
    multiThreading.start();
}

2. Implementing the Runnable

public class MultithreadingExample implements Runnable{

  @Overrid
    public void run(){
      for(int i=1; i<=5; i++){
            System.out.println(i);
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){}
        }
  }
}

//run it like this

public static void main(String[] args) {
    MultithreadingExample multiThreading = new MultithreadingExample();
    Thread thread = new Thread(multiThreading);
    thread.start();
}

Both examples will produce the same results. But if you extend the Thread class, the downside is that you will not be able to extend any other class. But if you implement the Runnable interface, then you could still extend any other class but implement multiple interfaces because Java allows that.

#programming #java #threads #asynchronous #coding #javascript #multithreading #go

#softwareengineering #softwarearchitecture #designpatterns

Thanks for reading!

Did you find this article valuable?

Support Adrian Kodja by becoming a sponsor. Any amount is appreciated!