INTRODUCTION :
A thread is defined as a separate stream of implementation that takes place simultaneously with and independently of everything else that might be happening. It does not have an event loop. A thread runs autonomously of anything else happening in the computer. With threads the other tasks that don't get stuck in the loop can continue processing without waiting for the stuck task to terminate. A thread is a coding that doesn't affect the architecture of an application. Threading is equally separate the computer's power among different tasks.
Threading concept is very important in Java Programing language. A thread is a sequential path of code execution within a program. And each thread has its own local variables, program counter and lifetime.
In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways : Using threads in Java will enable greater flexibility to programmers looking for that extra edge in their programs.
The simplicity of creating, configuring and running threads lets Java programmers devise portable and powerful applets/applications that cannot be made in other third-generation languages. Threads allow any program to perform multiple tasks at once. In an Internetaware language such as Java, this is a very important tool.
When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start () method, it doesn’t mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed.
Different states of a thread are :
In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways :
//Syntax: class MyThread extends Thread { }
//Syntax: MyThread implements Runnable { }
In short we have to follow following these steps :
The following program demonstrates a single thread creation extending the "Thread" Class :
class MyThread extends Thread { String s=null; MyThread(String s1) { s=s1; start(); } public void run() { System.out.println(s); } } public class RunThread { public static void main(String args[]) { MyThread m1=new MyThread("Thread started...."); } } //Output of the Program is: C:\>javac RunThread.java C:\>java RunThread Thread started....
Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows :
The following program demonstrates the thread creation implenting the Runnable interface :
class Thr1 implements Runnable{ Thread t; String s=null; Thr1(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s); } } public class RunableThread{ public static void main(String args[]){ Thr1 m1=new Thr1("Thread started...."); } } //Output: C:\>javac RunableThread.java C:\>java RunableThread Thread started....
However, this program returns the output same as of the output generated through the previous program.
preferable to extending the Thread Class :
The following program demonstrates the join() & isAlive() methods :
class DemoAlive extends Thread { int value; public DemoAlive(String str) { super(str); value=0; start(); } public void run() { try { while (value < 5) { System.out.println(getName() + ": " + (value++)); Thread.sleep(250); } } catch (Exception e) {} System.out.println("Exit from thread: " + getName()); } } public class DemoJoin { public static void main(String[] args) { DemoAlive da = new DemoAlive("Thread a"); DemoAlive db = new DemoAlive("Thread b"); try { System.out.println("Wait for the child threads to finish."); da.join(); if (!da.isAlive()) System.out.println("Thread A not alive."); db.join(); if (!db.isAlive()) System.out.println("Thread B not alive."); } catch (Exception e) { } System.out.println("Exit from Main Thread."); } } //Output: C:\>javac DemoJoin.java C:\>java DemoJoin Wait for the child threads to finish. Thread a: 0 Thread b: 0 Thread a: 1 Thread b: 1 Thread a: 2 Thread b: 2 Thread a: 3 Thread b: 3 Thread a: 4 Thread b: 4 Exit from thread: Thread a Thread A not alive. Exit from thread: Thread b Thread B not alive. Exit from Main Thread.
In Java, the threads are executed separately to each other. These types of threads are called as asynchronous threads. But there are two problems may be occurs with asynchronous threads.
Suppose, we have created two methods as increment( ) and decrement( ). which increases or decreases value of the variable "count" by 1 respectively shown as :
//Syntax public void increment( ) { count++; }
When the two threads are executed to access these methods (one for increment( ),another for decrement( )) then both will distribute the variable "count". in that case, we can't be sure that what value will be returned of variable "count".
We can see this problem in the diagram shown below :
To avoid this problem, Java uses monitor also known as “semaphore” to prevent data from being corrupted by multiple threads by a keyword synchronized to coordinate them and intercommunicate to each other. It is basically a mechanism which allows two or more threads to share all the available resources in a sequential manner. Java's synchronized is used to ensure that only one thread is in a critical region. Critical region is a lock area where only one thread is run (or lock) at a time. Once the thread is in its critical section, no other thread can enter to that critical region. In that case, another thread will has to wait until the current thread leaves its critical section.
General form of the synchronized statement is as :
//Syntax synchronized(object) { // statements to be synchronized }
Lock :
Lock term refers to the access approved to a particular thread that can access the shared resources. At any given time, only one thread can hold the lock and thereby have access to the shared resource. Every object in Java has build-in lock that only comes in action when the object has synchronized method code. By associating a shared resource with a Java object and its lock, the object can act as a guard, ensuring synchronized access to the resource. Only one thread at a time can access the shared resource guarded by the object lock.
Since there is one lock per object, if one thread has acquired the lock, no other thread can acquire the lock until the lock is not released by first thread. Acquire the lock means the thread currently in synchronized method and released the lock means exits the synchronized method.
Remember the following points related to lock and synchronization :
Any method is specified with the keyword synchronized is only executed by one thread at a time. If any thread wants to implement the synchronized method, firstly it has to obtain the objects lock. If the lock is already held by another thread, then calling thread has to wait.
Synchronized methods are useful in those situations where methods are executed concurrently, so that these can be intercommunicate control the state of an object in ways that can corrupt the state if. Stack implementations usually define the two operations push and pop of elements as synchronized, that’s why pushing and popping are mutually exclusive process.
For Example - if several threads were sharing a stack, if one thread is popping the element on the stack then another thread would not be able to pushing the element on the stack.
The following program demonstrates the synchronized method :
class Demo extends Thread{ static String msg[]={"This", "is", "a", "synchronized", "variable"}; Share(String threadname){ super(threadname); } public void run(){ display(getName()); } public synchronized void display(String threadN){ for(int i=0;i<=4;i++) try{ this.sleep(1000); }catch(Exception e){} } } public class SynThread1 { public static void main(String[] args) { Share t1=new Share("Thread One: "); t1.start(); Share t2=new Share("Thread Two: "); t2.start(); }} //Output of the program is: Thread One: variable Thread Two: This Thread Two: is Thread two: a Thread Two: synchronized Thread Two: variable C:\nisha>javac SynThread.java C:\nisha>java SynThread Thread One: This Thread One: is Thread One: a Thread One: synchronized Thread One: variable Thread Two: This Thread Two: is Thread two: a Thread Two: synchronized Thread Two: variable
All Rights Reserved. © 2024 BookOfNetwork