MultiThreading In Java
Multithreading in Java refers to the concurrent execution of multiple threads within a single Java program.
Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU.
Java provides built-in support for multithreading using the Thread class or implementing the Runnable interface.
Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java.
Each thread runs parallel to each other.
Mulitple threads don’t allocate separate memory area, hence they save memory.
Allso the context switching between two threads takes place in very less time.
Advantages of MultiThreading:-
Concurrency: Multithreading enables concurrent execution of multiple tasks within the same program, allowing for parallelism and efficient utilization of CPU resources. This leads to improved performance and faster execution times, especially on multi-core processors.
Responsiveness: Applications that use multithreading remain responsive even when performing intensive tasks. By executing tasks concurrently, the user interface (UI) can remain active, responsive, and interactable while background tasks run.
Resource Sharing: Threads within a process can share the same memory space, allowing for efficient communication and sharing of data between threads. This shared memory space facilitates cooperation and exchange of information among threads.
Efficient Task Handling: Multithreading is beneficial for handling multiple I/O-bound and CPU-bound tasks simultaneously. For example, in applications dealing with networking or file I/O, multithreading allows one thread to continue working while another is waiting for I/O operations to complete.
Scalability: Multithreading can enhance the scalability of applications, enabling them to handle more concurrent users or processes efficiently. Thread pools and executor frameworks help manage resources effectively, enabling better scalability.
Modular and Maintainable Code: It allows developers to divide complex tasks into smaller, manageable threads, making the code more modular and easier to maintain. Each thread can handle a specific part of the task, leading to better code organization.
Faster Response to Events: In event-driven applications, multithreading allows for quick response to various events. For instance, in GUI applications, different threads can handle user input, rendering graphics, and background computations simultaneously.
Utilization of Multiple Processors/Cores: With multithreading, applications can leverage the power of modern processors with multiple cores. By dividing tasks among threads, the application can fully utilize the available hardware resources.
Enhanced Throughput: Multithreading can significantly improve the throughput of applications, enabling them to handle more operations within a given time frame by executing tasks concurrently.
BuiltIn Methods In MultiThreading
In Java, multithreading is supported by the java.lang.Thread class, and there are several built-in methods provided by this class.
along with methods in other related classes (Object class and ThreadLocal class) that help manage threads and their behavior.
Thread Class Methods:
start(): Initiates the execution of a thread. The run() method of the thread is invoked after calling start().
run(): Contains the code that represents the thread's task. This method needs to be overridden in a thread subclass.
sleep(long millis): Causes the current thread to sleep for the specified duration in milliseconds.
join(): Waits for the thread on which it's called to terminate. It's possible to specify a timeout for this method.
interrupt(): Interrupts the thread, causing it to stop execution or exit from a waiting or sleeping state.
isAlive(): Checks if the thread is alive (has been started and not yet terminated).
yield(): Suggests to the scheduler that the current thread is willing to yield its current use of a processor.
setName(String name), getName(): Set or retrieve the name of the thread.
Other Methods Related to Thread Management:
wait(), notify(), notifyAll(): Methods from the Object class that facilitate inter-thread communication and synchronization.
Thread.currentThread(): Returns a reference to the currently executing thread.
Thread.sleep(): A static method to make the current thread sleep.
ThreadLocal Class Methods:
get(): Retrieves the value associated with the current thread.
set(T value): Associates a value with the current thread.
remove(): Removes the value associated with the current thread.
Creating Threads Using Thread Class:-
class Mythread1 extends Thread {
@Override
public void run() {
System.out.println("mythread1 started");
System.out.println("cooking started");
}
}
class Mythread2 extends Thread {
@Override
public void run() {
System.out.println("mythread2 started");
System.out.println("chatting with girlfreind");
}
}
class Mythread3 extends Thread {
@Override
public void run() {
System.out.println("mythread3 started");
System.out.println("walking with freind");
}
}
CreatingThread Using RunnableInterface:-
class MyRunnableThread1 implements Runnable {
public void run() {
System.out.println("thread 1 started");
System.out.println("bullet1 fired");
}
}
class MyRunnableThread2 implements Runnable {
public void run() {
System.out.println("thread 2 started");
System.out.println("bullet2 fired");
}
}
class MyRunnableThread{
public static void main(String[] args) {
MyRunnableThread1 bullet1=new MyRunnableThread1();
Thread gun1=new Thread(bullet1);
MyRunnableThread2 bullet2=new MyRunnableThread2();
Thread gun2=new Thread(bullet2);
gun1.start();
gun2.start();
System.out.println(gun1.isAlive());
System.out.println("1 "+ gun1.getPriority());
System.out.println(gun2.isAlive());
System.out.println(gun2.getPriority());
System.out.println(gun1.getState());
System.out.println(gun1.isDaemon());
System.out.println("ended");
}
}

No comments:
Post a Comment