Java Threads : Fundamentals of Multithreading

javathreadA thread is an execution of a small set of instructions that are independently managed by the operating system scheduler. Java supports multithreading, which means that a simple program is broken into parts and every part is executed simultaneously. The parts are modeled in such a way that it does not affect the running of other parts. It extends multitasking where the application is subdivided into operations called threads. These threads run parallel to each other. The operating system schedules the processing times of each thread.

JAVATHREAD

 Learn Java from scratch at Udemy.com

  • New: A new thread’s life cycle begins in a new state and remains in the state until a program calls the run method.
  • Runnable: the executing state of the thread. The thread is said to be in runnable state.
  • Waiting: The thread is said to be in waiting state when it waits for other thread’s execution to perform specific task. The thread can again fall into a runnable state when a program calls for it.
  • Timed Waiting: A runnable thread enters the waiting state for specific time interval and then it can transition back to the executing state after a specified waiting period of time.
  • Terminated: When the thread task is completed as required, it gets terminated. However, the thread cannot transition back to the runnable state from this state.

Since threads run parallel to each other, the priority of threads have to be set by the operating system to determine the order of thread execution. Thread priorities are in a range between one (MIN_PRIORITY) to ten (MAX_PRIORITY). By default, the thread priority is given by NORM_PRIORITY (value five). The thread with a higher priority is executed first since they are allocated processor-first.

Threads are created in two ways

  • Runnable Interface
  • Extending Thread Class

Implementing Runnable Interface

  • Step 1: First implement the run() method given by the Runnable interface. The run()method is the entry point of a thread and complete logic is placed inside this function.

public void run()

  • Step 2: Instantiate Thread object.

Thread(Runnable obj, String threadNam);

“obj” is the instance of the main class.

  • Step 3: After the creation of a thread object, you can call the start() method that in turn calls the run() method to run the thread.

void start()

 Learn advanced Java programming using a tutorial at Udemy.com

Example Using Runnable Interface

class RunnableDem implements Runnable

{

private Thread t1;

private String threadNam;

RunnableDem( String name)

{

threadNam = name;

System.out.println("Thread Creating " +  threadNam );

}

public void run() {

System.out.println("Thread Running " +  threadNam );

try

{

for(int x = 4; x> 0; x--)

{

System.out.println("Thread: " + threadNam + ", " + x);

Thread.sleep(50);

}

} catch (InterruptedException e) {

System.out.println(" Intruppted Thread " +  threadNam + " interrupted.");

}

System.out.println("Thread " +  threadNam + " exit.");

}

public void start ()

{

System.out.println("Starting " +  threadNam );

if (t1 == null)

{

t1= new Thread (this, threadNam);// New Thread is created

t1.start ();//run method is called

}

}

}


public class TestThread {

public static void main(String args[])

{

RunnableDem run1 = new RunnableDem( "Thread_1");//Object of Class is created

run1.start();//Start method is called

RunnableDem run2= new RunnableDem( "Thread_2"); // 2nd Object is  created

run2.start(); // start method is called

}

}

In the main method, the object of the class is created that calls the start method of the runnable interface. In the start method, a new thread is created and the run() method is called for the thread execution.

Learn the basics of Java programming using a tutorial at Udemy.com

By Extending the Thread Class

class ThreadDemo extends Thread  //Thread class  is extended

{

private Thread t;

private String threadNam;

 

ThreadDemo( String name)   /// Default Constructor of the Class

{

threadNam = name;

System.out.println("Thread Creating " +  threadNam );

}

public void run()  // Thread execution starts

{

System.out.println("Thread Running " +  threadNam );

try {

for(int i = 4; i > 0; i--) {

System.out.println("Thread: " + threadNam + ", " + i);


Thread.sleep(50);// Sleep  method takes the thread in time waiting state for 50 seconds

}

} catch (InterruptedException e) {

System.out.println("Thread " +  threadNam + " interrupted.");

}

System.out.println("Thread " +  threadNam + " exit.");

}


public void start ()

{

System.out.println("Thread Starting " +  threadNam );

if (t == null)

{

t = new Thread (this, threadNam);// thread is created

t.start ();

}

}

}


class TestThread {

public static void main(String args[]) {

ThreadDemo t11 = new ThreadDemo( "Thread_1");//Class object is created and Thread name is passed as arguments

t11.start();

ThreadDemo t21 = new ThreadDemo( "Thread_2");

t21.start();

}

}

Output

Thread Creating Thread_1

Thread Starting Thread_1

Thread Creating Thread_2

Thread Starting Thread_2

Thread Running Thread_1

Thread: Thread-1, 4

Thread Running Thread-2

Thread: Thread-2, 4

Thread: Thread-1, 3

Thread: Thread-2, 3

Thread: Thread-1, 2

Thread: Thread-2, 2

Thread: Thread-1, 1

Thread: Thread-2, 1

Thread Thread_1 exit.

Thread Thread_2 exit.

 

The object is created in the main method of the class and the start method is called. The start method creates a thread and calls the run method for thread execution.

Thread Control

Java provides a way of controlling the threads in the programs. A multithread program can be built which can stop, resume or suspend the threads. Following are the list of methods:

  • Public void suspend(): Suspends thread current state which can be resumed.
  • Public void stop(): Completely stops the thread
  • Public void resume(): Resumes the suspended thread
  • Public void wait(): Makes the thread wait until notify() method is invoked
  • Public void notify(): Wakes thread up from waiting state.

Example:

public class Thread2 implements Runnable

{

Thread t1;

int Count1;

boolean suspend=false;

public void run()

{

if(suspended)

t.resume();

else

t.suspend();

suspended = !suspended;

return true;

}

...

}

Once the stop() method terminates the execution of the thread, even the start() method cannot start it, so the sleep() method is used instead of it to pause the thread execution for some time. This is not a good practice as the thread becomes unavailable for that period of time. The suspend() method is used to pause the execution of thread temporarily and resume() method makes the suspended thread run again.