Thursday, October 3, 2019

INTRODUCTION TO JAVA THREADS

INTRODUCTION TO JAVA THREADS


Image result for java thread
Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
Multi threading has several advantages over Multiprocessing such as;
·         Threads are lightweight compared to processes
·         Threads share the same address space and therefore can share both data and code
·         Context switching between threads is usually less expensive than between processes
·         Cost of thread intercommunication is relatively low that that of process intercommunication
·         Threads allow different tasks to be performed concurrently.
The following figure shows the methods that are members of the Object and Thread Class.
THREAD CREATION
There are two ways to create thread in java;
·         Implement the Runnable interface (java.lang.Runnable)
·         By Extending the Thread class (java.lang.Thread)
IMPLEMENTING THE RUNNABLE INTERFACE
The Runnable Interface Signature
public interface Burnable {
void run();
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.

No comments:

Post a Comment

Which Python course is best for beginners?

Level Up Your Python Prowess: Newbie Ninjas: Don't fret, little grasshoppers! Courses like "Learn Python 3" on Codecade...