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:

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

And create the main class:

public class ThreadExample {
    public static void main(String [] argv) {  
        SampleThread thread = new SampleThread();
        thread.start();
    }
}

Output:

Message from SampleThread
Message from SampleThread
Message from SampleThread
Message 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:

class MyRunner implements Runnable {
    @Override
    public void run(){
        for(int i=0; i<4; i++) {
            System.out.println("Message from MyRunner");
        }
    } 
}

public class ThreadExample2 {
    public static void main(String [] argv) {  
        Thread thread = new Thread(new MyRunner());
        thread.start();
    }
}

or creating a anonymous Runnable class like:

public class ThreadExample3 {
    public static void main(String [] argv) {  
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                for(int i=0; i<4; i++) {
                    System.out.println("Message from MyRunner");
                }
            } 
        });
        thread.start();
    }
}

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

Message from MyRunner
Message from MyRunner
Message from MyRunner
Message 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:

Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus