X
    Categories: java

Runnable Interface || Thread in Java || Java example

 

In the previous blog on Thread we have seen the implementation of Thread in java.In this topic Runnable interface is used to run threads.

 

Runnable interface

Why do we need to use Runnable?

To use a thread we need to extend our class with Thread class and every class can extend only class in java i.e., multiple inheritance is not supported.

 

Runnable :

Consider two classes Abc(), Def() having implemented Runnable interface’s.

class Abc implements Runnable {

    @Override
    public void run() {

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

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

        }
    }
}

 

class Def implements Runnable {

    @Override
    public void run() {

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

            System.out.println("Def " + i);
        }
    }
}

 

To run the threads initialize the object of class and pass them to threads

Abc abc = new Abc();
Thread t1 =new Thread(abc);
t1.start();

 

Def def = new Def();
Thread t2 =new Thread(def);
t2.start();

 

class Abc implements Runnable {

    @Override
    public void run() {

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

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

        }
    }
}

 

class Def implements Runnable {

    @Override
    public void run() {

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

            System.out.println("Def " + i);
        }
    }
}

 

Start the threads

public class TestExample {

    public static void main(String args[]) {

        Abc abc = new Abc();
        Thread t1 =new Thread(abc);
        t1.start();
        
        Def def = new Def();
        Thread t2 =new Thread(def);
        t2.start();

    }
}

 

 

 

setName() :

Set names to the threads for differentiating between threads.

 

t1.setName("Thread one");

System.out.println("Thread Abc : "+t1.getName());
t2.setName("Thread two");

System.out.println("Thread Def : "+t2.getName());

 

 

setPriority() :

Set priority for the threads as stated below.

t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);

System.out.println("Thread 1 priority "+t1.getPriority());
System.out.println("Thread 2 priority "+t2.getPriority());

 

 

 

 

abhishek:
Related Post

This website uses cookies.