Java Threads: The Basics

Method 1: Write a class that implements the Runnable interface

(i) Put the thread code in the run() method.

(ii) Create a thread object by passing a Runnable object as an argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. Like this: (new Thread(new MyThread())).start();

Simple code sample as follows:

package javathread1;

class MyThread implements Runnable
{
    public void run()
    {
        //Display info about thread
	System.out.println(Thread.currentThread());
    }
}

public class JavaThread1 
{    
    public static void main(String[] args) 
    {
        // Create the thread
        Thread thread1 = new Thread(new MyThread(), "thread 1");
        
        // Start the thread
        thread1.start();        
    }
}

Method 2: Declare the class to be a Subclass of the Thread class

(i) Override the run() method from the Thread class to define the code executed by the thread.

(ii) Invoke the start() method inherited from the Thread class to make the thread eligible for running.

Code sample as follows:

package javathread1;

class MyThread extends Thread 
{
    public void run() 
    {
	//Display info about this particular thread
	System.out.println(Thread.currentThread().getName());
    }
}

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

Leave a Reply