What is a Thread?
A thread is basically a lightweight and the smallest unit of process or lightweight sub-process, Threads share the common memory space. Java uses threads by using a "Thread Class".
There are two types of threads, they are
user threads
daemon threads (daemon threads are used when we want to clean the application and are used in the background).
What are Advantages of single threads?
Reduces overhead in the application as single thread execute in the system. Also, it reduces the maintenance cost of the application.
Process Vs Thread:
PROCESS:
1.Program in execution is called process
2.Process is a heavy wait.
3.Process takes more time context switching.
4.Process takes more time in communication.
5.Each process has different address spaces.
6.Process are not dependent on each other.
7.It does not require synchronization.
8.Resource consumption is more in process.
9.Process requires more time creation.
10.Process takes more time in termination.
THREAD
1.The sub part (small task)of process is called is thread.
2.Thread is a light wait.
3.Thread takes less time context switching.
4.Thread takes less time in communication.
5.Thread share has same address spaces.
6.Threads are dependent on each other.
7.Threads may require synchronization.
8.Resource consumption is less in threads.
9.Thread requires less time creation.
10.Thread takes less time in termination.
Multitasking:
Performing multiple task at a single task, it increases the performance of CPU. There are two types of Multitasking:
1.Thread Based Multitasking (Multi Threading)
2.Process Based Multitasking (Multi Processing)
What is Multi-threading in Java?
Multi-threading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU, so that the idle time of CPU can be kept to minimum.
Multi-threaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other.
Multiple threads don't allocate separate memory area, hence they save memory also, context switching between threads takes less time.
What is the purpose of Multithreading?
The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread. Threads are lightweight sub-processes, they share the common memory space. In Multithreaded environment, programs that are benefited from multithreading, utilize the maximum CPU time so that the idle time can be kept to minimum.
The users are not blocked because threads are independent, and we can perform multiple operations at times.
As such the threads are independent, the other threads won't get affected if one thread meets an exception.
Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider.
The Lifecycle of a thread:
There are various stages/states of life cycle of thread as shown in above diagram:
1.New
2.Runnable
3.Running
4.Waiting
5.Dead
New: A thread that has not yet started will be in this state. In this phase, the thread is created using class "Thread class". It remains in this state till the program starts the thread. It is also known as born thread.
Runnable: A thread executing in the Java virtual machine is in this state. In this phase, the instance of the thread is invoked with a start() method. The thread control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the thread.
Running: Once the thread starts executing, then the state is changed to "running" state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
Waiting: A thread that is waiting indefinitely for another thread to perform a particular action is in this state. As there multiple threads are running in the application, there is a need for synchronization between threads. Hence, one thread has to wait, till the other thread gets executed. Therefore, this state is referred as waiting state.
Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in "dead state".
Note: A thread can be in only one state at a given point in time.
Multitasking vs Multithreading vs Multiprocessing vs parallel processing
Multitasking: Ability to execute more than one task at the same time is known as multitasking.
Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
How to create a thread in Java?
In java we can create a thread in two ways. They are:
1)By extending Thread class.
2)By implementing Runnable interface.
Few Methods Of Thread Class
getName(): It is used for Obtaining a thread’s name
getPriority(): Obtain a thread’s priority
isAlive(): Determine if a thread is still running
join(): Wait for a thread to terminate
run(): Entry point for the thread
sleep(): suspend a thread for a period of time
start(): start a thread by calling its run() method
Method 1: creation of thread by extending Thread class
Ex1:
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Now the thread is in running state.");
}
public static void main(String args[])
{
ThreadDemo obj=new ThreadDemo();
obj.start();
}
}
Output:
C:\Users\Student\Desktop\java prg>javac ThreadDemo.java
C:\Users\Student\Desktop\java prg>java ThreadDemo
Now the thread is in running state.
Method 2: creation of thread by implementing Runnable interface
import java.lang.*;
class UseRunnable implements Runnable
{
public void run()
{
System.out.println("Thread created..using Runnable interface");
}
public static void main(String[] args)
{
UseRunnable e = new UseRunnable();
Thread t1= new Thread(e);
System.out.println("Is Thread alive:"+t1.isAlive());
System.out.println("get the name of the Thread :"+t1.getName());
t1.start();
System.out.println("Is Thread alive:"+t1.isAlive());
System.out.println("get the state of the Thread :"+t1.getState());
System.out.println("get the Thread ID :"+t1.getId());
System.out.println("Thread Priority :"+t1.getPriority());
System.out.println("Current Thread :"+t1.currentThread());
System.out.println("Is Thread alive:"+t1.isAlive());
}
}
class UseRunnable implements Runnable
{
public void run()
{
System.out.println("Thread created..using Runnable interface");
}
public static void main(String[] args)
{
UseRunnable e = new UseRunnable();
Thread t1= new Thread(e);
System.out.println("Is Thread alive:"+t1.isAlive());
System.out.println("get the name of the Thread :"+t1.getName());
t1.start();
System.out.println("Is Thread alive:"+t1.isAlive());
System.out.println("get the state of the Thread :"+t1.getState());
System.out.println("get the Thread ID :"+t1.getId());
System.out.println("Thread Priority :"+t1.getPriority());
System.out.println("Current Thread :"+t1.currentThread());
System.out.println("Is Thread alive:"+t1.isAlive());
}
}
Output:
ubuntu@ubuntu:~$ javac UseRunnable.java
ubuntu@ubuntu:~$ java UseRunnable
Is Thread alive:false
get the name of the Thread :Thread-0
Is Thread alive:true
get the state of the Thread :RUNNABLE
get the Thread ID :8
Thread Priority :5
Thread created..using Runnable interface
Current Thread :Thread[main,5,main]
Is Thread alive:false
ubuntu@ubuntu:~$ java UseRunnable
Is Thread alive:false
get the name of the Thread :Thread-0
Is Thread alive:true
get the state of the Thread :RUNNABLE
get the Thread ID :8
Thread Priority :5
Thread created..using Runnable interface
Current Thread :Thread[main,5,main]
Is Thread alive:false
Method 2: creation of thread by implementing Runnable interface using WINDOWS
Ex2:
class UseRunnable implements Runnable
{
public void run()
{
System.out.println("Thread created..using Runnable interface");
}
public static void main(String[] args)
{
UseRunnable e = new UseRunnable();
Thread t1= new Thread(e);
t1.start();
System.out.println(t1.getState());
System.out.println(t1.isAlive());
System.out.println("Hi");
System.out.println(t1.getName());
System.out.println(t1.getPriority());
System.out.println(t1.currentThread());
System.out.println(t1.getId());
System.out.println(t1.getState());
System.out.println(t1.isAlive());
System.out.println("=====Created NewThread======");
Thread t2= new Thread(e);
t2.start();
System.out.println(t2.getState());
System.out.println(t2.isAlive());
System.out.println("Hi");
System.out.println(t2.getName());
System.out.println(t2.getPriority());
System.out.println(t2.currentThread());
System.out.println(t2.getId());
System.out.println(t2.getState());
System.out.println(t2.isAlive());
}
}
Output on windows:
C:\Users\Student\Desktop\java prg>javac UseRunnable.java
C:\Users\Student\Desktop\java prg>java UseRunnable
Thread created..using Runnable interface
RUNNABLE
false
Hi
Thread-0
5
Thread[main,5,main]
7
TERMINATED
false
=========Created New Thread===========
RUNNABLE
true
Thread created..using Runnable interface
Hi
Thread-1
5
Thread[main,5,main]
8
TERMINATED
false
Method 2: creation of thread by implementing Runnable interface using UBUNTU
Example:
class UseRunnable implements Runnable
{
public void run()
{
System.out.println("Thread created..using Runnable interface");
}
public static void main(String[] args)
{
UseRunnable e = new UseRunnable();
Thread t1= new Thread(e);
System.out.println("isalive"+t1.isAlive());
t1.start();
System.out.println(t1.getState());
System.out.println(t1.isAlive());
System.out.println("Hi");
System.out.println(t1.getName());
System.out.println(t1.getPriority());
System.out.println(t1.currentThread());
System.out.println(t1.getId());
System.out.println(t1.getState());
System.out.println(t1.isAlive());
System.out.println("=====Created NewThread======");
Thread t2= new Thread(e);
t2.start();
System.out.println(t2.getState());
System.out.println(t2.isAlive());
System.out.println("Hi");
System.out.println(t2.getName());
System.out.println(t2.getPriority());
System.out.println(t2.currentThread());
System.out.println(t2.getId());
System.out.println(t2.getState());
System.out.println(t2.isAlive());
System.out.println("=====Created NewThread======");
Thread t3= new Thread(e);
t3.start();
System.out.println(t3.getState());
System.out.println(t3.isAlive());
System.out.println("Hi");
System.out.println(t3.getName());
System.out.println(t3.getPriority());
System.out.println(t3.currentThread());
System.out.println(t3.getId());
System.out.println(t3.getState());
System.out.println(t3.isAlive());
}
}
{
public void run()
{
System.out.println("Thread created..using Runnable interface");
}
public static void main(String[] args)
{
UseRunnable e = new UseRunnable();
Thread t1= new Thread(e);
System.out.println("isalive"+t1.isAlive());
t1.start();
System.out.println(t1.getState());
System.out.println(t1.isAlive());
System.out.println("Hi");
System.out.println(t1.getName());
System.out.println(t1.getPriority());
System.out.println(t1.currentThread());
System.out.println(t1.getId());
System.out.println(t1.getState());
System.out.println(t1.isAlive());
System.out.println("=====Created NewThread======");
Thread t2= new Thread(e);
t2.start();
System.out.println(t2.getState());
System.out.println(t2.isAlive());
System.out.println("Hi");
System.out.println(t2.getName());
System.out.println(t2.getPriority());
System.out.println(t2.currentThread());
System.out.println(t2.getId());
System.out.println(t2.getState());
System.out.println(t2.isAlive());
System.out.println("=====Created NewThread======");
Thread t3= new Thread(e);
t3.start();
System.out.println(t3.getState());
System.out.println(t3.isAlive());
System.out.println("Hi");
System.out.println(t3.getName());
System.out.println(t3.getPriority());
System.out.println(t3.currentThread());
System.out.println(t3.getId());
System.out.println(t3.getState());
System.out.println(t3.isAlive());
}
}
Output on UBUNTU:
ubuntu@ubuntu:~/sudha$ javac UseRunnable.java
ubuntu@ubuntu:~/sudha$ java UseRunnable
isalivefalse
RUNNABLE
true
Hi
Thread-0
5
Thread[main,5,main]
8
RUNNABLE
true
=====Created NewThread======
RUNNABLE
true
Hi
Thread-1
5
Thread[main,5,main]
9
RUNNABLE
true
=====Created NewThread======
Thread created..using Runnable interface
Thread created..using Runnable interface
RUNNABLE
true
Hi
Thread-2
5
Thread[main,5,main]
10
RUNNABLE
true
Thread created..using Runnable interface
ubuntu@ubuntu:~/sudha$ java UseRunnable
isalivefalse
RUNNABLE
true
Hi
Thread-0
5
Thread[main,5,main]
8
RUNNABLE
true
=====Created NewThread======
RUNNABLE
true
Hi
Thread-1
5
Thread[main,5,main]
9
RUNNABLE
true
=====Created NewThread======
Thread created..using Runnable interface
Thread created..using Runnable interface
RUNNABLE
true
Hi
Thread-2
5
Thread[main,5,main]
10
RUNNABLE
true
Thread created..using Runnable interface
Thread Priorities
A
thread priority decides how one thread is to be treated with respect to
the other threads in an application. A thread priority is an integer
number.
About Thread Priorities in Detail
- Thread priorities are integer numbers.
- Using thread priority, we can decide when we should switch from one thread in running state to another. This is the context switching process wherein we switch contexts of the threads.
- Anytime a thread can voluntarily release its control over CPU. Then the thread with the highest priority can take over.
- Similarly, a higher priority thread can pre-empt any other thread with lower priority.
- Thread class provides a setPriority() method that is used to set the priority for the thread.
- We can also use constants MIN_PRIORITY, MAX_PRIORITY, or NORM_PRIORITY in the place of integers.
Example:
public class PrTest extends Thread{
public void run()
{
System.out.println("Child Thread ");
System.out.println("Child Thread Priority :"+Thread.currentThread().getPriority());
}
public static void main(String[] args)
{
System.out.println("Main Thread old Priority :"+Thread.currentThread().getPriority());
Thread.currentThread().setPriority(3);
System.out.println("Main Thread new Priority :"+Thread.currentThread().getPriority());
PrTest t = new PrTest();
t.start();
}
}
Note: instesd of setpriority(3) we can use
MIN_PRIORITY will display 1
MAX_PRIORITY will display 10
NORM_PRIORITY will display 5
Output:
import java.lang.*;
class Test1 extends Thread
{
public void run()
{
System.out.println("video playing ");
}
}
class Test2 extends Thread
{
public void run()
{
System.out.println("audio playing ");
}
}
class Test3 extends Thread
{
public void run()
{
System.out.println("status bar displaying ");
}
}
public class Testmul
{
public static void main(String args[])
{
Test1 t1 = new Test1();
t1.start();
Test2 t2 = new Test2();
t2.start();
Test3 t3 = new Test3();
t3.start();
}
}
ubuntu@ubuntu:~$ javac PrTest.java
ubuntu@ubuntu:~$ java PrTest
Main Thread old Priority :5
Main Thread new Priority :3
Child Thread
Child Thread Priority :3
ubuntu@ubuntu:~$ java PrTest
Main Thread old Priority :5
Main Thread new Priority :3
Child Thread
Child Thread Priority :3
Different cases of executing Threads:The following are the 4 ways to execute
1.Performing single task from single thread
2.Performing single task from multiple thread
3.Performing multiple task from single thread // it will not work
4.Performing multiple task from multiple thread
1. Program to illustrate no 1.Performing single task from single thread
public class Test extends Thread
{
public void run()
{
System.out.println("Now the thread is in running state.");
}
public static void main(String args[])
{
Test t1=new Test();
t1.start();
}
}
Output:
vl@ubuntu:~$ javac Test.java
vl@ubuntu:~$ java Test
Now the thread is in running state.
vl@ubuntu:~$ java Test
Now the thread is in running state.
2. Program to illustrate no 2.Performing single task from multiple thread
public class Test extends Thread
{
public void run()
{
System.out.println("Now the thread is in running state.");
}
public static void main(String args[])
{
Test t1=new Test();
t1.start();
Test t2=new Test();
t2.start();
Test t3=new Test();
t3.start();
}}
Output:vl@ubuntu:~$ javac Test.java
vl@ubuntu:~$ java Test
Now the thread is in running state.
Now the thread is in running state.
Now the thread is in running state.
vl@ubuntu:~$ java Test
Now the thread is in running state.
Now the thread is in running state.
Now the thread is in running state.
3. Program to illustrate no 3.Performing multiple task from single thread
We can not solve this case as single thread cannot work on multiple tasks
4. Program to illustrate no 4.Performing multiple task from multiple thread
class Test1 extends Thread
{
public void run()
{
System.out.println("video playing ");
}
}
class Test2 extends Thread
{
public void run()
{
System.out.println("audio playing ");
}
}
class Test3 extends Thread
{
public void run()
{
System.out.println("status bar displaying ");
}
}
public class Testmul
{
public static void main(String args[])
{
Test1 t1 = new Test1();
t1.start();
Test2 t2 = new Test2();
t2.start();
Test3 t3 = new Test3();
t3.start();
}
}
Output:
vl@ubuntu:~$ javac Testmul.java
vl@ubuntu:~$ java Testmul
video playing
audio playing
status bar displaying
vl@ubuntu:~$ java Testmul
video playing
audio playing
status bar displaying
Ex3:
class MulThread extends Thread
{
private int number;
//class constructor
public MulThread(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int numInt = 0;
//prints the number till specified number is reached, starting from 10
try
{
do
{
numInt = (int) (counter + 10);
System.out.println(this.getName() + " printing " + numInt);
Thread.sleep(1000);
counter++;
}while(numInt != number);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("**"+this.getName() + " Printed " + counter + " Times.**");
}
}
class UseMulThread
{
public static void main(String [] args)
{
System.out.println("Starting Thread1");
Thread t1 = new MulThread(15);
t1.start();
System.out.println("Starting Thread2");
Thread t2 = new MulThread(20);
t2.start();
}
}
Output:
C:\Users\Student\Desktop\java prg>javac MulThread.java
C:\Users\Student\Desktop\java prg>java UseMulThread
Starting Thread1
Starting Thread2
Thread-0 printing 10
Thread-1 printing 10
Thread-1 printing 11
Thread-0 printing 11
Thread-1 printing 12
Thread-0 printing 12
Thread-1 printing 13
Thread-0 printing 13
Thread-0 printing 14
Thread-1 printing 14
Thread-1 printing 15
Thread-0 printing 15
Thread-1 printing 16
**Thread-0 Printed 6 Times.**
Thread-1 printing 17
Thread-1 printing 18
Thread-1 printing 19
Thread-1 printing 20
**Thread-1 Printed 11 Times.**
No comments:
Post a Comment