Java Multithreading Basics: Multitasking & Thread Creation

📘 Java Learning – Multithreading (Part 1: Multitasking & Thread Creation) 🚀🎯 Starting my learning journey into Java Multithreading, one of the most powerful features of Java used for executing multiple tasks simultaneously. 🔰 Multitasking Executing several tasks simultaneously is called Multitasking. There are two types of multitasking: 👉 Process Based Multitasking 👉 Thread Based Multitasking 1️⃣ Process Based Multitasking Executing several tasks simultaneously where each task is a separate independent process. Example: Running multiple applications at the same time: • Browser • Music Player • Code Editor ✔ Best suited at Operating System level 2️⃣ Thread Based Multitasking (Multithreading) Executing several tasks simultaneously where each task is an independent part of the same program. Each independent path of execution is called a Thread. ✔ Best suited for Programmatic level 🎯 Objective of Multitasking • Improve system performance • Reduce response time 📌 Applications of Multithreading Multithreading is widely used in: • Video games • Multimedia graphics • Animations • High performance applications 🔰 Multithreading Support in Java Java provides rich API support for multithreading through: • Thread • Runnable • ThreadGroup • ThreadLocal ✔ Java provides built-in APIs for multithreading, and programmers use these APIs to create and manage threads. This makes multithreading easier in Java compared to C++. 🔰 Ways to Create a Thread A thread can be defined in two ways: 1️⃣ Extending Thread class 2️⃣ Implementing Runnable interface 📌 Example – Extending Thread Class class MyThread extends Thread { public void run() { for(int i=0;i<5;i++){ System.out.println("Child Thread"); } } } public class ThreadDemo { public static void main(String[] args) { MyThread t = new MyThread(); // instantiation of thread t.start(); // starting of a thread for(int i=0;i<5;i++){ System.out.println("Main Thread"); } } } 📌 start() does NOT directly execute run(). It does: start() ↓ JVM asks Thread Scheduler ↓ New Thread Created ↓ run() executes in new thread ⭐ Key Points • start() method creates a new thread • run() contains the task executed by thread • Multiple threads execute simultaneously More concepts like Thread Scheduler, start() vs run(), Thread Lifecycle in the next post. #Java #CoreJava #Multithreading #JavaDeveloper #Concurrency #LearningJourney

To view or add a comment, sign in

Explore content categories