Zach Cochran
by Zach Cochran
1 min read

Categories

Tags

I went ahead and started to look into multithreading in java tonight, because I know it’s going to be something I’ll need to understand fairly soon. I’m not sure if different libraries implement it without any real work on the users part, but I figured it would be good to start with the basics.

Everything here comes from a tutorial I found earlier on youtube. I’m not sure how great of a source this really is, but I liked that the example showed what all is required to get threading working in a super basic example.

So by default, java applications will run completely single threaded. Everything runs in the single main thread. When you’ve got failures within your program, you’ll notice that the failures are occuring within that main thread.

In order to make use of multi threading, classes have to be created extending threads. This will allow the method to be executed in its own thread, rather than being executed by main. In order for the threads to start, main will need to initially kick them off.

In addition to extending Thread, the class must also implement a run() method with what will be executed when the thread starts.

Finally, that thread will get started by main with a call to the start() method.

Here’s the simple program that shows how this all fits together:

// TO make a thread, you have to have the class extend thread, as well as start it back in main.
// We also have to supply a run method as that's what's going to be started by `start`
class Hi extends Thread {
   public void run() {
       for (int i = 0; i < 5; i++) {
           System.out.println("Hi");
           try {
               Thread.sleep(500);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }
}

class Hello extends Thread {
   public void run() {
       for (int i = 0; i < 5; i++) {
           System.out.println("Hello");
           try {
               Thread.sleep(500);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }
}

public class ThreadDemo {

   public static void main(String[] args) {

       // Everything by default is being done by the main thread.
       Hi obj1 = new Hi();
       Hello obj2 = new Hello();

       // These will run serially
       // obj1.show();
       // obj2.show();

       // These will run in parallel
       obj1.start();
       obj2.start();
   }
}

💚