Topics Index

ThreadDemo - Java Example Program

class ThreadDemo
    public static void main(String arg[])
        Thread threadOne = new Thread(); // LINE A
        System.out.println("Default Name: " + threadOne.getName());
        System.out.println("Default Priority: " + threadOne.getPriority() + "\n ");
        threadOne.setName("threadOne"); // setting name
        threadOne.setPriority(1); //setting minimum priority
        System.out.println("Current Name: " + threadOne.getName());
        System.out.println("Current Priority: " + threadOne.getPriority() + "\n ");
        System.out.println("ThreadID: " + threadOne.getId()); //returns unique Id
        System.out.println("threadOne isAlive: " + threadOne.isAlive() +"\n ");
        ClassImplementsRunnable td = new ClassImplementsRunnable();
        Thread runthread = new Thread(td, "runthread"); // LINE B
        runthread.start(); // LINE C    

class ClassImplementsRunnable implements Runnable {
    public void run() {
        System.out.println("i am running");

Default Name: Thread-0
Default Priority: 5

Current Name: threadOne
Current Priority: 1

ThreadID: 9
threadOne isAlive: false

i am running


In the above program at LINE A we have created a Thread with reference threadOne and set its name and priority using setName() and setPriority() methods. getId() of thread class returns the unique Id of the thread, this unique Id is generated by the JVM to identify the threads. At LINE B we used Thread(Runnable target, String name) constructor to create a thread for ClassImplementsRunnable object and invoked run() method of that class by calling start() method at LINE C.

  • Create thread with the name ThreadFirst using constructor Thread(String name) and set is priority to 10.
  • Display the priority of the ThreadFirst using getPriority() method.
  • Create one more thread for the ClassImplementRunnable class and invoke run() method.

© meritcampus 2019

All Rights Reserved.

Open In App