Create thread in Java

The Thread class is the main class for creating and executing thread in Java. We can use this class in two ways:

1. Create a subclass of Thread class and overriding it's run() method.
2. Create an instance of Runnable interface and creating a Thread object with this.

Note: The Thread class is also implementing Runnable interface.

Now let us see this two approaches with code examples:

1. Thread class with overriding run() method

Create a subclass named SampleThread extending Thread:

1public class SampleThread extends Thread {
2    @Override
3    public void run() {
4        for(int i=0; i<4; i++) {
5            System.out.println("Message from SampleThread");
6        }
7    }  
8}

And create the main class:

1public class ThreadExample {
2    public static void main(String [] argv) {  
3        SampleThread thread = new SampleThread();
4        thread.start();
5    }
6}

Output:

1Message from SampleThread
2Message from SampleThread
3Message from SampleThread
4Message from SampleThread

2. Runnable object with Thread object

In this approach we have to create an instance of Runnable interface. We can do this either by creating a concrete class implementing Runnable like this:

 1class MyRunner implements Runnable {
 2    @Override
 3    public void run(){
 4        for(int i=0; i<4; i++) {
 5            System.out.println("Message from MyRunner");
 6        }
 7    } 
 8}
 9
10public class ThreadExample2 {
11    public static void main(String [] argv) {  
12        Thread thread = new Thread(new MyRunner());
13        thread.start();
14    }
15}

or creating a anonymous Runnable class like:

 1public class ThreadExample3 {
 2    public static void main(String [] argv) {  
 3        Thread thread = new Thread(new Runnable(){
 4            @Override
 5            public void run(){
 6                for(int i=0; i<4; i++) {
 7                    System.out.println("Message from MyRunner");
 8                }
 9            } 
10        });
11        thread.start();
12    }
13}

For both the examples, the output would be same like:

1Message from MyRunner
2Message from MyRunner
3Message from MyRunner
4Message from MyRunner

Some useful methods of Thread class

  • void setName(String name): To set some name of the thread.
  • String getName(): To get the name of the thread.
  • void setPriority(int newPriority): To change the priority of the thread.
  • int getPriority(): To get current priority of the thread.
  • boolean isAlive(): To check whether the thread is still running or not.
  • void interrupt(): To interrupt the execution of the thread.
  • void join(): To wait for the thread execution to stop.

References:

comments powered by Disqus