Flat Preloader Icon

Threads

Overview

  • Defining Thread
  • Creating & Starting a Thread
  • Thread States
  • Preventing Thread Execution
  • Thread Sleeping
  • Thread priorities
  • Synchronization
  • Thread Interaction
In Java, threads are a fundamental part of the language and its libraries, allowing you to create and manage concurrent execution of tasks within a program. Java provides a built-in Thread class and a java.util.concurrent package for more advanced thread management.

Defining Threads

  • Extend class java.lang.Thread & Override run method E.g.:-
				
					class ThreadDemo extends Thread {
public void run() {
//your code
}
}
				
			
  • Implement java.lang.Runnable interface E.g:-
				
					class ThreadDemo implements Runnable {
public void run() {
//your code
 }
}
				
			

Creating & Starting Threads

  • When the class extends java.lang.Thread class E.g.:-
				
					ThreadDemo t = new ThreadDemo();
 t.start();
				
			
  • When the class implements java.lang.Runnable interface E.g.
				
					ThreadDemo obj = new ThreadDemo();
Thread t = new Thread(obj);
t.start();
				
			

Thread States

  • One of the following five states:-
    • New:-This is the state the thread is in after the Thread instance has been created, but the start() method has not been invoked on the thread.
    • Runnable:-This is the state a thread is in when it’s eligible to run, but the scheduler has not selected it to be the running thread. A thread first enters the runnable state when the start() method is invoked.
    • Running:-When the scheduler chooses the thread to be running as the current process.

    Thread States (Continued)

    • Waiting/Blocked/Sleeping:- This is the state where the thread is still alive but not eligible to run.
    • Dead:- This is the state when the run method of the Thread has completed its execution and it no longer remains a separate thread of execution.

    Preventing Thread Execution

  • Three scenario would be discussed :-
    • Thread is sleeping.
    • Thread is waiting.
    • Thread is blocked for acquiring an object’s lock.

    Thread sleeping

  • Sleep
    • Makes the running thread go into the sleep state for some specified time
  • Yield
    • Makes the current running thread give up the processor temporarily, but keeps the thread in runnable state.
  • Join
    • Makes the current thread wait for the end of execution of the thread it is joined to.

    Thread Priorities

  • Any number from 1 to 10
  • Uses the Thread class’ static method “setPriority(int val)”
  • Three static final variables hold these values:-
    • Thread.MIN_PRIORITY (1)
    • Thread.NORM_PRIORITY (5) (1)
    • Thread.MAX_PRIORITY (10) (1)