TIL: Two Ways to Create Java Threads
Tags: java, threads, todayilearned
Published: 2019-07-31 19:42:38

---
title: TIL: Two Ways to Create Java Threads
published: true
description: What I learned today about creating threads
tags: java, threads, TIL
---

<img src="https://miro.medium.com/max/2800/1*XyDxK63szQtYNSaiIzj13w.jpeg" alt="A bundle of threads">

One of Java’s most powerful features is how easily it allows one to manage threads for carrying out various tasks within a program. Used correctly, threads can make your program highly efficient.
That said, today I learned about the two ways in which one can create these threads:

<h2>First Method: Implementing Runnable</h2>

Runnable is an interface that abstracts executable code. Implementing Runnable and it’s method run(), we are able to create a functioning thread with ease:

``` java
class MyThread implements Runnable {
    Thread thread;

    MyThread() {
        thread = new Thread(this, "Sample Thread");
        thread.start();
    }
    public void run() {
        try {
            for(int i = 5; i > 0; i--) {
                System.out.println("child thread: " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("InterruptedException caught: Child Thread");
        }
        System.out.println("child thread exit");
    }
}

class MyThreadDemo {
    public static void main(String args[]) {
        new MyThread(); // Creates a new MyThread

        try {
            for(int i = 5; i > 0; i--) {
                System.out.println("main thread: " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("InterruptedException caught: Main Thread");
        }
        System.out.println("main thread exit");
    }
}
```

This is quite a lump of code to do something so simple, but keep in mind that most of this is to demo what is happening when the threads are running.

Running this code, the input is as follows:

```java
main thread: 5
child thread: 5
child thread: 4
main thread: 4
child thread: 3
main thread: 3
main thread: 2
child thread: 2
main thread: 1
child thread: 1
main thread exit
child thread exit
```

You may wonder why the threads do not maintain their execution order, and I would send you to read further on threads, specifically concerning serialization.

Implementing runnable, creating a thread, and then starting that thread has us up and running. It really is that simple.

<h2>Second Method: Extending a Thread</h2>

Less used for me personally is the practice of extending a pre-existing Thread. This has mostly been used when I am working with someone else’s tech, but do not have access to or permission to edit their source code.
Using the example previously shown I could do the following:

```java
class MyThread extends Thread{
   // Collapsed for the sake of brevity
}
class ThreadDemo {
  public static void main(String args[]) {
    new MyThread(); // create a new thread

    try {
      for(int i = 5; i > 0; i--) {
        System.out.println("main thread: " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("InterruptedException caught - main");
    }
    System.out.println("main thread exit.");
  }
}
```

Output would be similar:

```java
main thread: 5
child thread: 5
child thread: 4
main thread: 4
child thread: 3
child thread: 2
main thread: 3
child thread: 1
child thread exit
main thread: 2
main thread: 1
main thread exit
```

Again, this method is used mostly when working with code that I really don’t have access to. Most of the time implementing Runnable is the way to go.

Have a wonderful day!