Posts Java Multithreading - Starting Java Threads
Post
Cancel

Java Multithreading - Starting Java Threads

This following post is based on the Udemy Course: Java Multithreading


We can create threads either by extending the Thread class or by implementing the Runnable interface. Here is an example of how it would look like.

Extending Thread Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.learn;


class Runner extends Thread{

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

public class App {

 public static void main(String[] args) {
  
  Runner runner1 = new Runner();
  runner1.start(); //Don't call run method directly, otherwise it would just run in the main thread of the app
  
  Runner runner2 = new Runner();
  runner2.start();
  
 }
 
}

Implement Runnable Interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.demo;

class Runner implements Runnable{

 @Override
 public void run() {

  for(int i=0; i<10; i++) {

   System.out.println("Hi " + i);

   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }

  }

 }

}

public class MyApp {

 public static void main(String[] args) {

  Thread t1 = new Thread(new Runner());
  Thread t2 = new Thread(new Runner());
  
  t1.start();
  t2.start();
  
 }

}

Using Anonymous Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package demo3;

public class App {

 public static void main(String[] args) {
  
  Thread t1 = new Thread(new Runnable() {
   
   @Override
   public void run() {
    
    for(int i=0; i<10; i++) {

     System.out.println("Hey " + i);

     try {
      Thread.sleep(100);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }

    }
    
   }
  });
  
  t1.start();
  
 }

}
This post is licensed under CC BY 4.0 by the author.