What is Multithreading ?
Muthithreading is a part of Process that has ability to perform more than one job concurrently.
As you know main method is a main thread in Java from where your program execution is started but main thread can execute number of task one by one. If you want to execute multiple task at same time or concurrently so you need to create multiple thread from your main method.
Using Multithreading you can achieve multitasking.
There are two way to achieve multitasking:
- Multiprocessor Based
- Multithread Based
Both are the part of Operating System. So you can request to create a thread by Thread scheduler of OS.
Java supports multithreading not multiprocessing because of following reasons:
Process | Thread |
---|---|
Process is a group of threads. | Thread is part of process or sub process. |
Process is a heavy weight. | Thread is light weight. |
Process has own memory area. | Thread is part of process. |
Inter Process Communication is high expensive. | Inter Thread Communication is low expensive. |
Process effects the main memory. | Thread effects the process memory. |
Note: In Java by default provide a process so you dont need to worried about process that means you just create a thread and perform your task.
Thread Scheduler
Thread Scheduler responsibility of maintaining the sequence of execution of threads, where which thread should be given first preference than others.
The scheduling is depends on the algorithm of the scheduler like Preemitive and Time Slicing with Round Robin etc.
Preemitive Scheduling : The highest priority task executes until it enters the waiting or dead state or a higher priority task comes into existence.
Time Slicing : A task executes for a predefine slice of time and then reenters the pool of ready task.
Why Multithreading ?
Multithreading is used to utilize the full CPU power.
Using Multithreading you can execute multiple task at same time.
Using Multithreading you can save your time of execution.
Using Multithreading you can reduce response time.
Using Multithreading serve the resources to the multiple client at same time.
When you use Multithreading ?
Multithreading is used when you have limited resources.
For Example:
A single Shopping Web Site can be access by multiple clients at the same time here that particular Shopping site is a single resource(limited resource).
What is Thread ?
Thread is light weight sub process.
Every thread has own stack where you can define separate thread task.
You can create own Threads to perform multiple task at same time.
There are two way to create a Thread:
- By extending Thread class
- By implementing Runnable Interface
1. By extending Thread Class
Thread is a predefine class in Java that exist in java.lang package.
You can use a Thread when you want to use only thread resources because in this case you can not extends more than one class.
Thread class also implements Runnable interface.
In case of Thread you need to override run() method to define a task executing by your thread and call the start() method to create a thread by thread scheduler.
Thread class provide following methods:
Type | Method with description |
---|---|
Thread | Thread.currentThread()
Return the current running thread object. |
long | getId()
Return the identifier of this Thread. |
String | getName()
Return the name of this Thread. |
String | getPriority()
Return the priority of this Thread between 1 to 10. |
Thread.State | getState()
Return the state of this Thread(NEW, RUNNABLE, BLOCKED, WAITING, TERMINATE etc). |
ThreadGroup | getThreadGroup()
Return the ThreadGroup object of this Thread to get group name etc. |
boolean | isAlive()
Return the status of thread is live or terminate. |
boolean | isDaemon()
Check this thread is a Daemon(service) thread or not. |
boolean | isInterrupted()
Tests whether this thread has been interrupted. |
void | join()
Wait for this thread to die(terminate). |
void | run()
In this you can define a task that you want to executed by this thread. |
void | setDaemon(boolean on)
Marks this thread as a Daemon thread or user thread. |
void | setName(String name)
You can set the name of this thread. |
void | setPriority(int priority)
You can set the priority between 1 to 10 or use Constant Variable like MAX_PRIORITY, MIN_PRIORITY and NORM_PRIORITY. |
void | start()
Causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread. |
void | Thread.sleep(long milliseconds)
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. |
void | Thread.yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor. |
Thread Examples:
Hello World program.public class Test extends Thread { @Override public void run() { System.out.println("Hello World"); } public static void main(String[] args) { new Test().start(); } }
Result: Hello World
How to Get Current Thread.
public class Test{ public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); } }
Result: main
How to check Thread is created or not.
public class Test extends Thread{ @Override public void run(){ System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { new Test().start(); } }
Result: Thread-0
If you not call the start() method.
public class Test extends Thread{ @Override public void run(){ System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { new Test().run(); } }
Result: main
Note : if you call the run method directly then there is no new thread created. So this task executed by the main thread.
If you call the start() method twicely.
public class Test extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Test t = new Test(); t.start(); t.start(); } }
Result: Thread-0
IllegalThreadStateException
Note : If you call start() method twicely with the same object then you will get an IllegalThreadStateException.
How to create multiple thread.
public class Test extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Test t1 = new Test(); t1.start(); Test t2 = new Test(); t2.start(); } }
Result: Thread-0
Thread-1
2. By implementing Runnable Interface
Runnable is a predefine interface in Java that exist in java.lang package.
Runnable interface has run() method only.
You can use Runnable interface when you want to another class resource and thread resource.
You need to implements Runnable interface in your class and override run() method to define a task.
How to create thread using Runnable Interface
Runnable Example :public class Test implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Test t = new Test(); // here implemented class is called runnable target // runnable target object associated by Thread class Thread tt = new Thread(t); tt.start(); } }
Result: Thread-0
How to create multiple thread
public class Test implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Test t = new Test(); // here implemented class is called runnable target // runnable target object associated by Thread class Thread tt0 = new Thread(t); tt0.start(); Thread tt1 = new Thread(t); tt1.start(); } }
Result: Thread-0
Thread-1
Note: You can use any one way to create a thread based on your requirements.
No comments:
Post a Comment