Skip to main content

How to create thread

There are 2 ways to create a thread:

  1. By extending Thread class
  2. By implementing Runnable interface
create thread

1- Extending Thread class

MyThread.java

public class MyThread extends Thread {

	public void run() {
		for (int i = 1; i <= 5; i++) {
			System.out.println("Counter- " + i);
		}
	}
}

Test.java

public class Test {

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

Output:

Counter- 1
Counter- 2
Counter- 3
Counter- 4
Counter- 5

2- Implementing Runnable interface

MyThread.java

public class MyThread implements Runnable {

	public void run() {
		for (int i = 1; i <= 5; i++) {
			System.out.println("Counter- " + i);
		}
	}
}

Test.java

public class Test {

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

Output:

Counter- 1
Counter- 2
Counter- 3
Counter- 4
Counter- 5

References

  1. Java Thread Tutorial: Creating Threads and Multithreading in Java

Leave a Reply

Your email address will not be published. Required fields are marked *

Top