Provide Best Programming Tutorials

Java Thread

Thread Class Introduction

The java.lang.Thread class is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Following are the important points about Thread −

  • Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority

  • Each thread may or may not also be marked as a daemon.

  • There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread and,

  • the other way to create a thread is to declare a class that implements the Runnable interface

The figure below shows the class diagram for the Thread class.

Since the Thread class implements Runnable, you could define a class that extends Thread and implements the run method

Create a new thread and start it

You can create a new thread by defining a class extends Thread class.

You can then invoke the start() method to tell the JVM that the thread is ready to run, as follows:thread.start();

Take a look at the code below we define a class called CustomThread ,this class extends Thread class and override its run method.

In the threadClass we create a new instance of it and call its start method to run this thread.

package multithreading;

public class threadClass {

    public static void main(String[] args) {
        CustomThread customThread = new CustomThread();
        //start a new thread

class CustomThread extends Thread {
    public void run() {
        System.out.println("Hello i am a custom thread!");

join() method in thread

A new thread4 is created and it prints character c 40 times. The numbers from 50 to 100 are printed after thread thread4 is finished.

Thread priority

Java assigns every thread a priority. By default, a thread inherits the priority of the thread that spawned it. You can increase or decrease the priority of any thread by using the setPriority method, and you can get the thread’s priority by using the getPriority method. Priorities are numbers ranging from 1 to 10 . The Thread class has the int constants MIN_PRIORITY , NORM_PRIORITY , and MAX_PRIORITY , representing 1 , 5 , and 10 , respectively. The priority of the main thread is Thread.NORM_PRIORITY.

The JVM always picks the currently runnable thread with the highest priority. A lowerpriority thread can run only when no higher-priority threads are running. If all runnable threads have equal priorities, each is assigned an equal portion of the CPU time in a circular queue. This is called round-robin scheduling .


Leave a Reply

Close Menu