MultiThreading
1. Ways to define multi threading
a. By extending thread class
b. By implementing runnable class
2. Getting and setting name of thread
3. Thread priorities
4. Method to prevent thread execution
5. Synchronization
6. Inter thread communication
7. Deadlock
8. Deamon threads
9. Multithreading enhancements
Introduction:
Multi-tasking
Executing several tasks simultaneously is a concept of multi-tasking. There are two
types of multi-tasking.
1. Process based muli-tasking ⇒ Program independent of other
2. Thread based multitasking ⇒ Same program running as multiple independent
parts.
Advantages:
1. To reduce response time of the system and improve the performance of the system.
Usage:
1. Multiple media animation
2. Video games
3. Web apps eg ⇒ gmail
Java provides internal support for Multithreading with rich API(thread, runnable and
threadgroup) compared to old languages developing multi threaded application is easy.
Thread
● A thread is responsible for flow of execution. Every thread is associated with
some jobs.
● A thread can be defined in two ways.
○ By extending the thread class.
○ By implementing the runnable class.
Defining a thread:
● A Thread is defined by extending a Thread class and Overriding the run method
Initiating and defining a thread:
● A thread will be initiated by creating a new instance MyThread t = new MyThread();
● t.start() will be used to run the thread.
● Default only one thread will be executed.
● Main thread will initiate the child thread and start the main thread.
Thread scheduler
1. Thread scheduler is a part of JVM
2. Its is responsible to schedule threads, if multiple threads are waiting to be executed,
then the order of thread execution is based on the thread scheduler.
3. No exact algorithm followed by scheduler, it varies from JVM to JVM, hence we can't
expect thread execution order and exact output.
4. In multi threading there is no exact output, there are several possible outputs.
Diff b/w Start() and run().
1. If run is directly called, then it’ll be run by a normal thread by main thread.
To Importance of thread.start().
It is responsible to register thread with thread scheduler and all other mandatory
activities,