THREADS
-------
definition:-
A Thread represents a process (or) execution of group of statements.
ex:// which is currently running Thread?
class MyClass{
public static void main(String args[]){
System.out.println("This is first line");
Thread t = Thread.currentThread();
System.out.println("Current Thread:" + t);
System.out.println("Its name:" +t.getName());
}
}
O/P:- This is first line
current Thread:Thread[main,5,main]
Its name :main
->Main thread is default Thread that executes the statements in a java program.
->5 is the default priority number.
Execution of statements is of Two types:-
----------------------------------------
1.Single Tasking:-
--------------
Executing only one task at a time by the Micro-Processor is called single tasking.
.Much of the processor time is wasted in single tasking.
2.Multi-tasking:-
--------------
time slice:-
It represents a unit of time alloted for a task.
Round Robin:-
Executing the first task after the last task in cyclic manner is called round robin method.
Executing Multiple tasks simultaneously by the processor is called Multi-tasking.
Advantage:Here processor time is not wasted.i.e the processor time is utilized in an optimum(better) way.
There are two ways of multi-tasking:-
1.Process based Multi-tasking:-
In this Multiple processes (or) programs are executed by the processor at a time.
2.Thread based Multi-tasking:-
In this several parts of same program are executed by the processor at a time using threads.
diagram:-
IIQ)What is the difference between process and Thread?
r)A thread is a light weight process.It uses less resources of the System.
(light weight -> less memory,less time)
A process is a heavy weight process.It uses high resources of the system.
Uses of Threads:-
---------------
->Threads are used in server side programs to provide services to several clients at a time.
->Threads are used in animations and games.
Creating a Thread:-
-----------------
1.Create a class as a sub class to Thread class (or) create a class as an implementaion class of 'Runnable' interface.
ex:- class Myclass extends Thread
class Myclass implements Runnable
2.write public void run() in the class.
Note:- A thread will recognise and execute only run() method.
3.create an object to the class
ex:- Myclass obj = new Myclass();
4.create a Thread and attatch it to the object.
ex:- Thread t = new Thread(obj);
5.Now run the Thread.
ex:- t.start();
IIQ)How can you stop a thread in the middle?
a)1.create a boolean type variable and store false in it.
ex:- boolean stop = false;
2.If the variable value is true,return from public void run() method.
ex: if(stop) return;
3.When the user wants to stop the thread,store true into the variable.
ex:- //stop thread when Enter pressed
System.in.read();
obj.stop = true;
ex:- //creating a thread and running it.
*class Theatre extends Thread
*class Theatre implements Runnable
IIQ)What is the difference between extends Thread and Implements Runnable?
r)Functionally both are same.When we extends Thread class there is no scope to extend another class.
ex:- class Myclass extends Thread,class1 //invalid
When we implement Runnable interface.there is still scope to extend another class.
ex:- class Myclass extends class1 implements Runnable //valid
So,implements Runnable is more advantageous than extends Thread.
Multi-tasking with two threads:-
------------------------------
In multi-tasking,several tasks are executed at a time.For this purpose, we need more than one thread.
For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks.Then those tasks are simultaneously executed by the two threads.
Using more than one thread is called 'multi threading'.
ex:-
Multiple Threads acting on one object:-
-------------------------------------
But in this case, sometimes we get unreliable results.
ex:-
Thread Synchronization:-
-----------------------
When a Thread acts on an object,any other Threads are not allowed to act upon the same object simultaneously this is called Thread Synchronization.
The object on which the Threads are synchronized is called Mutex(mutually exclusive lock).
Thread synchronization (or) Thread Safe is done in 2 ways.
1.We can synchronize a block of statements using synchronized block.
ex:- synchronized(obj){
Statments;
}
2.We can use Synchronized keyword before a method to Synchronize the entire method.
ex:- synchronized return type method(){
method body;
}
IIQ)What is the difference between sysnchronized block and synchronized key word?
r) synchronized block is useful to synchronize a block of statements.Synchronized key word is useful to synchronize an entire method.
Threads:-
A Thread represents a process (or) execution of a group of statements.
Creating a Thread:-
-----------------
Thread t1 = new Thread();
//Thread is created without any name.
Thread t2 = new Thread(obj);
//Here , obj is target object of the Threadl
Thread t3 = new Thread(obj,"Thread-name");
//target Object and Thread name are given
Thread class methods:-
---------------------
1.To know the currently running Thread:-
Thread t = Thread.currentThread();
2.To start a Thread:-
t.start();
3.To stop execution of a Thread for a specified time:-
Thread.sleep(milliseconds);
4.To get the name of a Thread:-
String name = t.getName();
5.To set a new Name to Thread:-
t.setName("new name");
6.To get the priority of a Thread:-
int priority_no = t.getPriority();
7.To set the priority of a Thread:-
t.setPriority(int priority_no);
Note:- Thread priorities can change from 1 to 10.
We can also use the following constants to represents priorities.
Thread.MAX_PRIORITY value is 10
Thread.MIN_PRIORITY value is 1
Thread.NORM_PRIORITY value is 5
8.To test if a Thread is still alive:-
t.isAlive() returns true/false.
9.To wait till a Thread dies:-
t.join();
Thread DeadLock:-
----------------
When a Thread wants to act upon an object which is locked by another thread,and the second thread wants to act upon the object which is already locked by the first thread, both the threads will continue in waiting state forever.Which is called 'Thread DeadLock'.
when deadlock occurs further processing of the program is halted.
ex:- //To cancle a Ticket.
ex:- //To book a ticket.
ex:- //cancle and book tickets.
IIQ)What is the solution for Thread DeadLock?
r)There is no solution for Thread deadLock.The programmer should design the logic in such a way that it will not involve the Thread DeadLock.
ex:-
Thread communication:-
---------------------
In some cases,two or more threads should communicate with each other.
ex:- a Consumer thread is waiting for a Producer to produce the data(or some goods). when he Producer thread completes production of data,then the Consumer thread should take that data and use it.
diagram:-
ex:- // write a program such that the consumer thread is informed immediately when the data production is over.
Object class methods:-
--------------------
1.To send a notification to a waiting thread:-
obj.notify();
2.To send notification to all waiting Threads:-
obj.notifyAll();
3.To wait till the obj is released(till notification is received)
obj.wait();
Note:-Microsoft peope announced that notify() and wait() methods should be used with in Synchronized block.
IIQ)What is the difference between the sleep() and wait() methods?
r) 1.Both the sleep() and wait() methods are used to suspend a thread execution for a specified time.
2.When sleep() method is executed inside a synchronized block, the object is still under lock.
3.When wait() method is executed inside a synchronized block, It breaks that block, so that the object lock is removed and it is available.
->generally,sleep() is used for making a thread to wait for some time.
But wait() method is used in Connection with notify() or notifyAll() methods in thread communication.
Thread Priorities:-
------------------
ex:// w.a.p to understand the thread priorities.The thread with higher priority number will complete its execution first.
Thread Group:-
-------------
A Thread group represents several threads as a single group.The main advantage of taking several threads as a group is that by using a single method, we will be able to control all the threads in the group.
->To create a Thread group:-
ThreadGroup tg = new ThreadGroup("groupname");
here tg is thread group object,and groupname is its name.
->To add a thread to this group(tg):-
Thread t1 = new Thread(tg,targetobj,"threadname");
Here t1 is child thread,This thread acts on target object
->To add another threadGroup to the group 'tg':
ThreadGroup tg1 = new ThreadGroup(tg,"groupname");
->To know the parent of a thread (or) A thread group:-
tg1.getParent(); //output:tg
->To know the parent thread group of a thread:-
t1.getThreadGroup();
->To know the no of Threads actively running in a thread group:-
tg.activeCount();
->To change the maximum priority of a thread group tg:-
tg.setMaxPriority();
ex://W.a.p to demonstrate the creation of thread groups and some
// methods which act on thread groups.
Daemon Threads:-
--------------
Some times,A Thread has to continuously execute without any interruption to provide services to other threads.Such threads are called daemon threads.
IIQ)what is daemon thread?
r)A daemon thread is a thread that executes continuously.Daemon threads are service providers for other threads (or) objects.It generally provides a background processing.
-->To make a thread t as daemon thread:-
t.setDaemon(true);
-->To know if a Thread is daemon thread or not:-
boolean x = t.isDaemon();
Thread LifeCycle:-
-----------------
diagram:-
-------
IIQ)What is Thread LifeCycle?
r) A Thread is created using new Thread() statement and is executed by start() method.The thread enters 'runnable' state and when sleep() (or) wait() methods are used (or) when the Thread is blocked on I/O,it then goes into 'not runnable' state.From 'not runnable' state,The Thread comes back to the 'runnable' state and continues running the statements.The Thread dies when it comes out of run() method.These state transitions are called 'life cycle of a thread'
-------
definition:-
A Thread represents a process (or) execution of group of statements.
ex:// which is currently running Thread?
class MyClass{
public static void main(String args[]){
System.out.println("This is first line");
Thread t = Thread.currentThread();
System.out.println("Current Thread:" + t);
System.out.println("Its name:" +t.getName());
}
}
O/P:- This is first line
current Thread:Thread[main,5,main]
Its name :main
->Main thread is default Thread that executes the statements in a java program.
->5 is the default priority number.
Execution of statements is of Two types:-
----------------------------------------
1.Single Tasking:-
--------------
Executing only one task at a time by the Micro-Processor is called single tasking.
.Much of the processor time is wasted in single tasking.
2.Multi-tasking:-
--------------
time slice:-
It represents a unit of time alloted for a task.
Round Robin:-
Executing the first task after the last task in cyclic manner is called round robin method.
Executing Multiple tasks simultaneously by the processor is called Multi-tasking.
Advantage:Here processor time is not wasted.i.e the processor time is utilized in an optimum(better) way.
There are two ways of multi-tasking:-
1.Process based Multi-tasking:-
In this Multiple processes (or) programs are executed by the processor at a time.
2.Thread based Multi-tasking:-
In this several parts of same program are executed by the processor at a time using threads.
diagram:-
IIQ)What is the difference between process and Thread?
r)A thread is a light weight process.It uses less resources of the System.
(light weight -> less memory,less time)
A process is a heavy weight process.It uses high resources of the system.
Uses of Threads:-
---------------
->Threads are used in server side programs to provide services to several clients at a time.
->Threads are used in animations and games.
Creating a Thread:-
-----------------
1.Create a class as a sub class to Thread class (or) create a class as an implementaion class of 'Runnable' interface.
ex:- class Myclass extends Thread
class Myclass implements Runnable
2.write public void run() in the class.
Note:- A thread will recognise and execute only run() method.
3.create an object to the class
ex:- Myclass obj = new Myclass();
4.create a Thread and attatch it to the object.
ex:- Thread t = new Thread(obj);
5.Now run the Thread.
ex:- t.start();
IIQ)How can you stop a thread in the middle?
a)1.create a boolean type variable and store false in it.
ex:- boolean stop = false;
2.If the variable value is true,return from public void run() method.
ex: if(stop) return;
3.When the user wants to stop the thread,store true into the variable.
ex:- //stop thread when Enter pressed
System.in.read();
obj.stop = true;
ex:- //creating a thread and running it.
*class Theatre extends Thread
*class Theatre implements Runnable
IIQ)What is the difference between extends Thread and Implements Runnable?
r)Functionally both are same.When we extends Thread class there is no scope to extend another class.
ex:- class Myclass extends Thread,class1 //invalid
When we implement Runnable interface.there is still scope to extend another class.
ex:- class Myclass extends class1 implements Runnable //valid
So,implements Runnable is more advantageous than extends Thread.
Multi-tasking with two threads:-
------------------------------
In multi-tasking,several tasks are executed at a time.For this purpose, we need more than one thread.
For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks.Then those tasks are simultaneously executed by the two threads.
Using more than one thread is called 'multi threading'.
ex:-
Multiple Threads acting on one object:-
-------------------------------------
But in this case, sometimes we get unreliable results.
ex:-
Thread Synchronization:-
-----------------------
When a Thread acts on an object,any other Threads are not allowed to act upon the same object simultaneously this is called Thread Synchronization.
The object on which the Threads are synchronized is called Mutex(mutually exclusive lock).
Thread synchronization (or) Thread Safe is done in 2 ways.
1.We can synchronize a block of statements using synchronized block.
ex:- synchronized(obj){
Statments;
}
2.We can use Synchronized keyword before a method to Synchronize the entire method.
ex:- synchronized return type method(){
method body;
}
IIQ)What is the difference between sysnchronized block and synchronized key word?
r) synchronized block is useful to synchronize a block of statements.Synchronized key word is useful to synchronize an entire method.
Threads:-
A Thread represents a process (or) execution of a group of statements.
Creating a Thread:-
-----------------
Thread t1 = new Thread();
//Thread is created without any name.
Thread t2 = new Thread(obj);
//Here , obj is target object of the Threadl
Thread t3 = new Thread(obj,"Thread-name");
//target Object and Thread name are given
Thread class methods:-
---------------------
1.To know the currently running Thread:-
Thread t = Thread.currentThread();
2.To start a Thread:-
t.start();
3.To stop execution of a Thread for a specified time:-
Thread.sleep(milliseconds);
4.To get the name of a Thread:-
String name = t.getName();
5.To set a new Name to Thread:-
t.setName("new name");
6.To get the priority of a Thread:-
int priority_no = t.getPriority();
7.To set the priority of a Thread:-
t.setPriority(int priority_no);
Note:- Thread priorities can change from 1 to 10.
We can also use the following constants to represents priorities.
Thread.MAX_PRIORITY value is 10
Thread.MIN_PRIORITY value is 1
Thread.NORM_PRIORITY value is 5
8.To test if a Thread is still alive:-
t.isAlive() returns true/false.
9.To wait till a Thread dies:-
t.join();
Thread DeadLock:-
----------------
When a Thread wants to act upon an object which is locked by another thread,and the second thread wants to act upon the object which is already locked by the first thread, both the threads will continue in waiting state forever.Which is called 'Thread DeadLock'.
when deadlock occurs further processing of the program is halted.
ex:- //To cancle a Ticket.
ex:- //To book a ticket.
ex:- //cancle and book tickets.
IIQ)What is the solution for Thread DeadLock?
r)There is no solution for Thread deadLock.The programmer should design the logic in such a way that it will not involve the Thread DeadLock.
ex:-
Thread communication:-
---------------------
In some cases,two or more threads should communicate with each other.
ex:- a Consumer thread is waiting for a Producer to produce the data(or some goods). when he Producer thread completes production of data,then the Consumer thread should take that data and use it.
diagram:-
ex:- // write a program such that the consumer thread is informed immediately when the data production is over.
Object class methods:-
--------------------
1.To send a notification to a waiting thread:-
obj.notify();
2.To send notification to all waiting Threads:-
obj.notifyAll();
3.To wait till the obj is released(till notification is received)
obj.wait();
Note:-Microsoft peope announced that notify() and wait() methods should be used with in Synchronized block.
IIQ)What is the difference between the sleep() and wait() methods?
r) 1.Both the sleep() and wait() methods are used to suspend a thread execution for a specified time.
2.When sleep() method is executed inside a synchronized block, the object is still under lock.
3.When wait() method is executed inside a synchronized block, It breaks that block, so that the object lock is removed and it is available.
->generally,sleep() is used for making a thread to wait for some time.
But wait() method is used in Connection with notify() or notifyAll() methods in thread communication.
Thread Priorities:-
------------------
ex:// w.a.p to understand the thread priorities.The thread with higher priority number will complete its execution first.
Thread Group:-
-------------
A Thread group represents several threads as a single group.The main advantage of taking several threads as a group is that by using a single method, we will be able to control all the threads in the group.
->To create a Thread group:-
ThreadGroup tg = new ThreadGroup("groupname");
here tg is thread group object,and groupname is its name.
->To add a thread to this group(tg):-
Thread t1 = new Thread(tg,targetobj,"threadname");
Here t1 is child thread,This thread acts on target object
->To add another threadGroup to the group 'tg':
ThreadGroup tg1 = new ThreadGroup(tg,"groupname");
->To know the parent of a thread (or) A thread group:-
tg1.getParent(); //output:tg
->To know the parent thread group of a thread:-
t1.getThreadGroup();
->To know the no of Threads actively running in a thread group:-
tg.activeCount();
->To change the maximum priority of a thread group tg:-
tg.setMaxPriority();
ex://W.a.p to demonstrate the creation of thread groups and some
// methods which act on thread groups.
Daemon Threads:-
--------------
Some times,A Thread has to continuously execute without any interruption to provide services to other threads.Such threads are called daemon threads.
IIQ)what is daemon thread?
r)A daemon thread is a thread that executes continuously.Daemon threads are service providers for other threads (or) objects.It generally provides a background processing.
-->To make a thread t as daemon thread:-
t.setDaemon(true);
-->To know if a Thread is daemon thread or not:-
boolean x = t.isDaemon();
Thread LifeCycle:-
-----------------
diagram:-
-------
IIQ)What is Thread LifeCycle?
r) A Thread is created using new Thread() statement and is executed by start() method.The thread enters 'runnable' state and when sleep() (or) wait() methods are used (or) when the Thread is blocked on I/O,it then goes into 'not runnable' state.From 'not runnable' state,The Thread comes back to the 'runnable' state and continues running the statements.The Thread dies when it comes out of run() method.These state transitions are called 'life cycle of a thread'
No comments:
Post a Comment