[vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]

Threads in Java

[/vc_column_text][vc_separator type=”normal” up=”1″][vc_column_text css=”.vc_custom_1570018020898{background-color: #f6f6f6 !important;}”]

The so called Threads in Java handles the order of priority for how a program should executes the code. 

[/vc_column_text][vc_empty_space height=”30px”][vc_column_text]

What are Threads in Java?

Most programs execute using only one thread that handles the priority order for how the program should execute. But what if multiple operations need to be performed exactly at the same time? By creating several threads that run in parallel, this can be made possible. This functionality is useful in more extensive programs (for example, in a multiplayer game that needs to handle multiple inputs simultaneously).

 

A thread in Java can be declared in two different ways,

 

  • By inheriting the extend class Thread
  • Implement the Runnable interface

 

We will, of course, look at how we do for both of them. But first, there is a difference between them that are good to know,

 

  • If we inherit the class Thread then we cannot inherit any other class. Java does not support so-called multiple inheritances as one class inherits code from multiple classes (remember inheritance?). However, if we use the Runnable interface, we can still inherit from a class.

 

In our game, we will only need one thread. We have chosen to use the Runnable interface in our game and is what we usually use when working with Threads.[/vc_column_text][vc_empty_space height=”20px”][vc_column_text]

[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal”][vc_empty_space height=”10px”][vc_column_text]

WHY USE THREADS IN JAVA?

We could view it as Threads enables multitasking. We use threads in Java to make the program faster by doing several things at once. Furthermore, additional uses could be when we want to treat multiple users at the same time. For example, a program that will take care of customers on a website. When shopping online, you do not want to wait in a long queue for others to finish before you can complete your order.

 

Finally, by enabling multitasking, we can respond more quickly to the information a user provides to the program. For example, if we have a GUI to draw something based on what the user is doing. If this happens sequentially and the program must wait all the time until the user is completely clear, and then the user must wait until the GUI finishes with the operation. If we use threads in Java, we can execute it in parallel and perform each of the tasks running side by side.[/vc_column_text][vc_empty_space height=”20px”][vc_separator type=”normal”][vc_empty_space height=”10px”][vc_column_text]

Declare a Thread using the Thread class

We create a thread by inheriting (extends) the Thred class where the run() method is defined.

 

The syntax for declaring a Thread by inheriting the class is,

 

import java.lang.*;

// Inherit Thread
public class Counter extends Thread      
{
        // Declare a new Thread
        Thread T; 

        // The order in which the program should be executed                           
        public void run()                     
        {                              
        ....            
        }
}

[/vc_column_text][vc_empty_space height=”30px”][vc_column_text]

[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal”][vc_empty_space height=”10px”][vc_column_text]

Declare a Thread in Java with the Runnable Interface

In a similar way, a thread can be created by implementing (implements)Runnable where the run() method is defined.

 

The Syntax to create a Thread in Java with Runnable is:

 

import java.lang.*;

// Implements Runnable
public class Counter implements Runnable {

        // Creates a new thread
        Thread T;                             

        // The order in which the program should be executed
        public void run() {                              

        ....            

        }
}

[/vc_column_text][vc_empty_space height=”20px”][vc_separator type=”normal”][vc_empty_space height=”10px”][vc_column_text]

How do we use Threads in Java?

There are a couple of different states a thread can have,

 

  • New: First, when a new thread is declared, it is the New state. The thread has not yet begun to execute when it is in this state.
  • Runnable: When the thread is ready to start executing, it moves to the Runnable state. You can see it as if the thread is waiting for the green light to run.
  • Running: As the name implies, it is in the Running state that the thread is executed.
  • Note Runnable: In this state, the thread does not run and takes no power from the computer CPU. The difference with Runnable is that in Runnable, the thread takes CPU power from the computer as it waits to executed. However, it does not when in the Not Runnable state. A thread in this state cannot continue execution until it is moved to the running state.
  • Terminated: The thread ends in this state. Normally, because of the entire code for the thread has been implemented by the program. But it may also be due to some unusual and unforeseen event that created an error.

 

The image below shows examples of how we can use some of the different methods available to create a thread. Note how we have different states and can use the methods to customize the state of our threads.[/vc_column_text][vc_empty_space height=”50px”][vc_single_image image=”20100″ img_size=”large” alignment=”center” onclick=”link_image” qode_css_animation=””][vc_empty_space height=”40px”][vc_column_text]

[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal”][vc_empty_space height=”10px”][vc_column_text]

Methods for Threads in Java

 

  • start(): Creates a new thread that will use the run() method. So if you want to create a new thread to start executing, use start(). However, would you rather use an existing thread and execute, use run()

 

  • run(): Used to start executing the thread. The method will not create any new thread but will only run existing threads. Note, the run() method only works with the Runnable interface

 

  • sleep(): Pauses the current executing thread (suspend execution) for the specified time

 

  • yield(): You can view it as this thread doesn’t do anything critical, and if we need to run any other threads or processes, they should go first. Otherwise, the program will run the current thread.

 

  • wait(): The thread is paused and waiting to be “awakened” again. Note that the current thread will then wait until another thread uses the notify() or notifyAll()  methods to wake it again. In general, you can say that the program uses sleep() to control the time of a thread and wait() for multi-thread synchronization

 

  • interrupt(): Every time we use interrupt() for a thread, it should stop what task it is performing. It is very likely that when the thread receives an interrupt(), it should end. There is no natural way to end a thread prematurely (before the thread completes), as past methods proved to have problems. But the interrupt() method seems to be the most widely used and recommended.

 

 

For a complete list of methods for the Runnable interface see the Oracle website[/vc_column_text][vc_empty_space height=”40px”][vc_column_text]

[/vc_column_text][vc_empty_space height=”20px”][vc_separator type=”normal”][vc_empty_space height=”20px”][/vc_column][/vc_row][vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]

Previous Page    |    Next Page

[/vc_column_text][vc_empty_space][/vc_column][/vc_row]