📘 Java Learning – Multithreading (Part 3: Runnable Interface, Thread Names & Priorities) 🚀🎯 Continuing my learning journey into Java Multithreading. In this post, I explored how to define threads using the Runnable interface, along with concepts like thread names and priorities. 🔰 Defining a Thread using Runnable Interface A thread can also be defined by implementing the Runnable interface, which is present in the java.lang package and contains only one method: • run() 📌 Two Approaches to Define a Thread 1️⃣ Extending Thread class 2️⃣ Implementing Runnable interface 📌 Example – Runnable Implementation class MyRunnable implements Runnable { public void run() { System.out.println("Child Thread"); } public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); System.out.println("Main Thread"); } } ✔ Output may appear in mixed order because execution depends on the Thread Scheduler. 🔰 Best Approach to Define a Thread Between the two approaches, implementing Runnable is recommended. Reason: • If a class extends Thread, it cannot extend any other class • If a class implements Runnable, it can still extend another class ✔ This provides better flexibility in design. 🔰 Common Thread Constructors Some commonly used constructors of the Thread class: Thread() Thread(Runnable r) Thread(String name) Thread(Runnable r, String name) Thread(ThreadGroup g, String name) Thread(ThreadGroup g, Runnable r) Thread(ThreadGroup g, Runnable r, String name) Thread(ThreadGroup g, Runnable r, String name, long stackSize) 🔰 Getting and Setting Thread Name Every thread in Java has a name (default or programmer-defined). Methods used: • getName() • setName(String name) Example: System.out.println(Thread.currentThread().getName()); // main Thread.currentThread().setName("first thread"); System.out.println(Thread.currentThread().getName()); To get the current executing thread reference: Thread.currentThread() 🔰 Thread Priority Every thread has a priority ranging from 1 (lowest) to 10 (highest). Standard constants: • Thread.MIN_PRIORITY • Thread.NORM_PRIORITY • Thread.MAX_PRIORITY If two threads have the same priority, the execution order depends on the Thread Scheduler. 🔰 Default Priority • Default priority of main thread → 5 • Child threads inherit priority from the parent thread Methods used: • getPriority() • setPriority(int p) Example: t.setPriority(5); t.setPriority(10); t.setPriority(100); // IllegalArgumentException ⭐ Key Takeaways • Threads can be created using the Runnable interface • Implementing Runnable offers better design flexibility • Every thread has a name and priority • Priority range: 1 to 10 Learning multithreading step by step while strengthening Java fundamentals ☕💻 #Java #CoreJava #Multithreading #JavaDeveloper #Concurrency #LearningJourney
Java Multithreading with Runnable Interface & Thread Names & Priorities
More Relevant Posts
-
Day 6-7 of Learning Java : Today I started my journey into Java programming which is taught by Aditya Tandon Sir. Here are the key concepts I learned today: Conditional Statements In Java:- Java uses conditional statements to decide which block of code should execute based on condition is true or false. Types:- • If statement • If else statement • Else If ladder • Switch statement • The Ternary Operator ∆ If statement:-The most basic control flow statement. It executes a block of code only if the given condition is true. Example:- if (age >= 18) { System.out.println("You are eligible to vote."); } ∆ If else statement:-It executes a block of code, when if condition is false, the else block runs. Example:- if (score >= 50) { System.out.println("Pass"); } else { System.out.println("Fail"); } ∆ Else If ladder:-When you have multiple conditions to check, you use a ladder. Java tests them from top to bottom and executes the first one that is true. Example:- int score = 85; if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { System.out.println("Grade: B"); } else { System.out.println("Grade: F (Fail)"); } ∆ The switch Statement:-Instead of a long chain of else if statements, a switch is comparing a single variable against a list of constant values. Example:- int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } ∆ The Ternary Operator (? :):-This is a shorthand of the if-else statement. It is the only operator in Java that takes three operands. Syntax: variable = (condition) ? value_if_true : value_if_false; This is just the beginning. Excited to continue this journey Special thanks to Rohit Negi bhaiya & Aditya Tandon Sir. #Day6 #Java #Coding #Learning #Consistency
To view or add a comment, sign in
-
-
🚀 Day 33 | Core Java Learning Journey 📌 Topic: File Handling in Java Today, I explored File Handling in Java — how applications store and retrieve data from files. This is a very important concept for building real-world applications where data persistence is required. 🔹 What is File Handling? ✔ File Handling is used to store data permanently in files ✔ It allows Java applications to read, write, and modify files ✔ Available through the java.io package 🔹 Why We Use File Handling? ✔ To store data permanently (even after program ends) ✔ To read existing data from files ✔ To build data-driven applications ✔ Used in logging, reports, configs, etc. 🔹 Important Classes in java.io.* ✔ File → Represents file or directory ✔ FileWriter → Writes data to file (character stream) ✔ FileReader → Reads data from file ✔ BufferedWriter → Efficient writing (faster) ✔ BufferedReader → Efficient reading (line by line) ✔ FileInputStream → Reads binary data ✔ FileOutputStream → Writes binary data ✔ InputStreamReader → Converts byte stream → character stream 🔹 Steps to Work with Files ✔ Step 1: Import package • import java.io.*; ✔ Step 2: Create File Object • File file = new File("test.txt"); ✔ Step 3: Write Data • FileWriter fw = new FileWriter(file); • fw.write("Hello Students"); ✔ Step 4: Read Data • FileReader fr = new FileReader(file); ✔ Step 5: Close Resources • Always close streams → fw.close(), fr.close() 🔹 Important Methods ✔ createNewFile() → Creates new file ✔ exists() → Checks file existence ✔ delete() → Deletes file ✔ write() → Writes data ✔ read() → Reads single character ✔ readLine() → Reads line (BufferedReader) ✔ flush() → Clears buffer and forces write ✔ close() → Closes stream 🔹 Key Concepts ✔ Buffered Streams → Faster performance ⚡ ✔ Character Streams → FileReader, FileWriter ✔ Byte Streams → FileInputStream, FileOutputStream ✔ Exception Handling → Must handle IOException ✔ Try-with-resources → Recommended (auto close) ✅ 🔹 Example (Best Practice) ✔ Using try-with-resources: • try (FileWriter fw = new FileWriter("test.txt")) { fw.write("Hello Students"); } 🔹 Store & Fetch Data ✔ Store → Using FileWriter / BufferedWriter ✔ Fetch → Using FileReader / BufferedReader ✔ Supports both text and binary data 📌 When to Use File Handling? ✅ When saving user data locally ✅ When working with logs or reports ✅ When database is not required ✅ When handling configuration files 💡 Key Takeaway: File Handling is essential for data persistence in Java. Understanding streams and proper resource management helps build efficient and reliable applications. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #FileHandling #JavaIO #Programming #LearningJourney
To view or add a comment, sign in
-
-
Day 43/200 - Java Learning Journey 🌱 ✨ Sharing what I learned today in Java. 🔆Dream big, start small, act now. 📚 Today I learned about Conditional Statements in java. Today's Topic: Conditional Statements (else-if) 📍 Else-if: 👉 It will be used when we have more than 2 condition to be checked. 👉 If the first if condition is false, Java checks the else if condition. 👉 Syntax: if(condition1) { // Executes if condition1 is true } else if(condition2) { // Executes if condition1 is true } else if(condition3) { // Executes if condition1 is true } else { // Executes if all above conditions are false } 👉 In if-else ,else-if "else" is an optional but better to follow for readability purpose. 👉 In both if-else ,else-if block "if" block is mandatory. Example: Grade Checker public class GradeCheck { public static void main(String[] args) { int marks = 75; if (marks >= 90) { System.out.println("Grade: A"); } else if (marks >= 75) { System.out.println("Grade: B"); } else if (marks >= 60) { System.out.println("Grade: C"); } else if (marks >= 40) { System.out.println("Grade: D"); } else { System.out.println("Grade: F (Fail)"); } System.out.println("End of program."); } } Ouput: Grade: B End of program. #Java#DailyLearning#Consistency#Else-if#ConditionalStatements#Meghana M#10000 Coders#
To view or add a comment, sign in
-
🚀 Day 31 | Core Java Learning Journey 📌 Topic: HashMap & Map Implementations (Internal Working + Concepts) Today, I deep-dived into how HashMap actually works internally along with LinkedHashMap, TreeMap, and Hashtable. This helped me understand not just usage, but the logic behind performance. 🔹 What is HashMap? ✔ HashMap is a class that implements Map interface ✔ Stores data in key-value pairs ✔ Allows one null key and multiple null values ✔ Not synchronized (not thread-safe) 🔹 Internal Working of HashMap ✔ Default initial capacity = 16 (bucket size) ✔ Data is stored in buckets (array of nodes) ✔ Each key’s hashCode() is used to find bucket index ✔ Formula: index = hash(key) & (n - 1) ✔ If two keys have same bucket index → Collision occurs 👉 Collision Handling: • Uses Linked List (before Java 8) • Uses Linked List + Balanced Tree (after Java 8) • If bucket size > 8 → converts into Red-Black Tree • If reduced → converts back to Linked List ✔ Load Factor = 0.75 (default) ✔ When threshold exceeds → resizing (rehashing) happens 🔹 Important Concepts ✔ Bucket → Each index of internal array ✔ Hashing → Converting key into integer hash ✔ Collision → Multiple keys at same index ✔ Rehashing → Increasing size & redistributing data 🔹 LinkedHashMap ✔ Extends HashMap ✔ Maintains insertion order ✔ Uses doubly linked list internally ✔ Slightly slower than HashMap 🔹 TreeMap ✔ Implements NavigableMap ✔ Stores keys in sorted order (natural/custom comparator) ✔ Uses Red-Black Tree internally ✔ Does NOT allow null key 🔹 Hashtable ✔ Legacy class (introduced before collections framework) ✔ Thread-safe (synchronized) ✔ Does NOT allow null key or value ✔ Slower due to synchronization 🔹 Key Differences ✔ HashMap → Fastest, no ordering ✔ LinkedHashMap → Maintains insertion order ✔ TreeMap → Sorted data ✔ Hashtable → Thread-safe but slower 📌 When to Use What? ✅ Use HashMap → Best performance, general use ✅ Use LinkedHashMap → Order matters ✅ Use TreeMap → Sorted output required ✅ Use Hashtable → Thread-safe (but prefer ConcurrentHashMap in modern Java) 💡 Key Takeaway: Understanding internal working of HashMap (buckets, hashing, collisions, rehashing) helps write optimized and scalable code instead of just using it blindly. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #HashMap #LinkedHashMap #TreeMap #Hashtable #JavaCollections #Programming #LearningJourney
To view or add a comment, sign in
-
-
📅 Day 38 & 39 – Java Learning Journey | ArrayList (Java Collections Framework) 🚀 In the past two days, I explored ArrayList, one of the most commonly used classes in the Java Collection Framework. Understanding how it works internally helps write efficient and optimized Java programs. 🔹 What is ArrayList? ArrayList is a dynamic array implementation in Java that can automatically grow or shrink in size. Unlike traditional arrays, we don't need to define the size in advance. 🔹 Default Capacity & Internal Resizing When an ArrayList is created: ArrayList<Integer> list = new ArrayList<>(); • Default capacity = 10 • When the array becomes full, Java increases capacity by 50% Formula used internally: newCapacity = oldCapacity + (oldCapacity / 2); Example growth: 10 → 15 → 22 → 33 → 49 → ... Example: import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); System.out.println(fruits.get(1)); // Access element } } 🔹 Common Operations in ArrayList ✔ Insertion ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); System.out.println(fruits); Output: [Apple, Banana, Mango] ✔ Accessing Elements System.out.println(fruits.get(1)); Output: Banana ArrayList allows fast access using index. ✔ Updating Elements fruits.set(1, "Orange"); System.out.println(fruits); Output: [Apple, Orange, Mango] ✔ Deleting Elements fruits.remove("Apple"); or fruits.remove(1); Output: [Orange, Mango] ✔ Size of ArrayList System.out.println(fruits.size()); 🔹 Time Complexity of ArrayList Operation TimeComplexity Add element (end)O(1) (Amortized) Access elementO(1) Update elementO(1) Insert element (middle)O(n) Delete elementO(n) Search elementO(n) 💡 Key Takeaways ✔ Dynamic resizing ✔ Maintains insertion order ✔ Allows duplicate values ✔ Null insertion is Possible ✔ Provides fast access with indexes Learning how these internal mechanisms work helps us choose the right data structure while building real-world applications. 🙏 Special thanks to my mentor Suresh Bishnoi from Kodewala Academy for guiding me step by step in my Java Backend Developer journey. #Java #JavaCollections #ArrayList #BackendDevelopment #100DaysOfCode #LearningInPublic #JavaDeveloper
To view or add a comment, sign in
-
-
Day 42/200 - Java Learning Journey 🌱 ✨ Sharing what I learned today in Java. 🔆Success is built on discipline, consistency, and hard work. 📚 Today I learned about Conditional Statements in java. Today's Topic: Conditional Statements (if-else) 📍 If-Else: 👉 Else will be executed when all the conditions becomes false. 👉 if, if-else is going to check only one condition at a time 👉 It will execute if block (or) else block not both. 👉 if-else Statement – Executes one block if the condition is true, otherwise executes another block. 👉 Syntax: if(condition){ //Code to execute if condition is true } else{ // Code to execute if condition is false } 👉 The if-else statement is used when we want to execute one block of code if the condition is true and another block if the condition is false. Example: public class IfElseExample { public static void main(String[] args) { int number = -5; if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is not positive."); } System.out.println("End of program."); } } O/p: The number is not positive. End of program. #Java#DailyLearning#Consistency#If-else#ConditionalStatements#Meghana M#10000 Coders#
To view or add a comment, sign in
-
Day 47/200 - Java Learning Journey 🌱 ✨ Sharing what I learned today in Java. 🔆Keep learning, keep growing. 📚 Today I learned about Jumping statements in Java Today's Topic: Jumping statements 📌 Jumping statements: 👉 The execution of the statements will be jumped, or skipped based on certain conditions. 👉 They are: 1.break 2.continue 3.return 📍 break: 👉 It is used to stop the flow of execution ,as per the condition. 👉Syntax: break; Example: Break on Number 3 public class BreakExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i == 3) { break; } System.out.println(i); } } } Output: 1 2 📍 continue: 👉 It is used to skip the current iteration. Example: Skip Number 3 public class ContinueExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; } System.out.println(i); } } } Output: 1 2 4 5 📍 return Statement: 👉 The return statement is used to exit from a method. It can also return a value if the method is not void. 👉 Syntax(no value): return; 👉 Syntax (with value): return value; Example 1: Return from void Method public class ReturnVoid { public static void greet() { System.out.println("Hello!"); return; // Any code here will not be executed } public static void main(String[] args) { greet(); } } Output: Hello! Example 2: Return Value from Method public class ReturnValue { public static int square(int num) { return num * num; } public static void main(String[] args) { int result = square(4); System.out.println("Square: " + result); } } Output: Square: 16 #Java#DailyLearning#Consistency#JumpingStatements#Meghana M#10000 Coders#
To view or add a comment, sign in
-
Day 41/200 - Java Learning Journey 🌱 ✨ Sharing what I learned today in Java. 🔆Learn a little every day, and one day you will realize how far you’ve come. 📚 Today I learned about Conditional Statements in java Today's Topic: Conditional Statements (if) 📍 Conditional Statements : 👉 These are also known as Decision Making Statements. 📍 If: 👉 The condition which is passed within the if will always check the boolean values and also the resultant will be boolean value. 👉 It is used to check only the one condition. 👉 Executes a block of code only if the condition is true. 👉 Syntax: if (condition){ //stmts } 📌 if(condition) without curly braces ,in that time the condition will be applied to the first line of the statement. Example 1: Checking if a number is positive or not. public class IfExample { public static void main(String[] args) { int number = 10; if (number > 0) { // Checks if the number is greater than 0 System.out.println("The number is positive."); } System.out.println("End of program."); } } O/p: The number is positive. End of program. Example 2: if Statement Skipping Execution. public class IfExample { public static void main(String[] args) { int number = -5; if (number > 0) { // This condition is false System.out.println("The number is positive."); } System.out.println("End of program."); } } O/p: End of program. #Java#DailyLearning#Consistency#ConditionalStatements#Meghana M#10000 Coders#
To view or add a comment, sign in
-
🚀 Java Learning Progress – Key Features from Java 8 → Java 21 As part of strengthening my Java fundamentals, I revised the major improvements introduced in different Java versions. Here is a simple summary from Java(LTS) 8 to Java 21 that helped me understand the evolution of the language. ☕ Java 8 (2014) – Functional Programming in Java Major shift in Java programming style. Key Features • Lambda Expressions • Stream API • Functional Interfaces • Default & Static methods in Interfaces • New Date & Time API Example – Lambda Expression List<Integer> list = Arrays.asList(1,2,3,4); list.forEach(n -> System.out.println(n)); Why it matters ✔ Less boilerplate code ✔ Functional programming style ✔ Powerful data processing with Streams ☕ Java 11 (2018) – Modern HTTP Client & Utilities Java 11 is an LTS (Long Term Support) version. Key Features • New HTTP Client API • String utility methods (isBlank, lines, strip) • Files.readString() • Run Java without compilation Example – HTTP Client HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://example.com")) .build(); Why it matters ✔ Easier REST API calls ✔ Cleaner String handling ☕ Java 17 (2021) – Modern Object-Oriented Features Another LTS version widely used in enterprise applications. Key Features • Sealed Classes • Pattern Matching for instanceof • Enhanced Switch Expressions • Strong encapsulation of JDK internals Example – Pattern Matching if (obj instanceof String s) { System.out.println(s.toUpperCase()); } Why it matters ✔ Cleaner and safer code ✔ Reduced type casting ☕ Java 21 (2023) – High Performance Concurrency Latest LTS version. Key Features • Virtual Threads (Project Loom) • Record Patterns • Pattern Matching for switch • Sequenced Collections Example – Virtual Thread Thread.startVirtualThread(() -> { System.out.println("Hello from Virtual Thread"); }); Why it matters ✔ Handle millions of concurrent requests ✔ Great for microservices and cloud systems 📌 My Key Takeaway Java has evolved from object-oriented programming → functional programming → modern concurrency. Understanding these features helps in writing clean, scalable, and high-performance applications. #Java #JavaDeveloper #LearningInPublic #SoftwareEngineering #Java8 #Java11 #Java17 #Java21
To view or add a comment, sign in
-
🚀 Day 25 | Core Java Learning Journey 📌 Topic: ArrayList & LinkedList in Java Today I learned about ArrayList and LinkedList, two important classes in the Java Collections Framework that implement the Java List Interface. Both are used to store ordered collections of elements, but they use different internal data structures and have different performance characteristics. 🔹 ArrayList ✔ ArrayList is a dynamic (growable) array implementation of the List interface. ✔ It automatically resizes when elements are added or removed. ✔ It allows duplicate elements and maintains insertion order. ✔ Elements can be accessed quickly using an index. Internal Data Structure: • Uses a resizable array. 📌Key Features: ✔ Fast random access using index (get, set operations) ✔ Allows null values and duplicate elements ✔ Maintains insertion order ✔ Automatically increases capacity when needed Best Use Case: ✔ When frequent data access (reading) is required. Example Implementation: • ArrayList 🔹 LinkedList ✔ LinkedList is another implementation of the List interface. ✔ It stores elements using nodes connected through links. ✔ Each node contains data and references to other nodes. ✔ It also implements Deque, so it can be used as a queue or stack. Internal Data Structure: • Doubly Linked List Each node contains: • Data • Reference to the previous node • Reference to the next node 📌Key Features : ✔ Efficient insertion and deletion of elements ✔ Allows duplicate elements ✔ Maintains insertion order ✔ Can be used as List, Queue, or Deque 🔹Types of Linked Lists (Conceptually): • Singly Linked List – Node points to next node • Doubly Linked List – Node points to both previous and next node • Circular Linked List – Last node connects back to the first node In Java, LinkedList is implemented as a Doubly Linked List. Example Implementation: • LinkedList 📌 Key Differences ✔ ArrayList uses a dynamic array ✔ LinkedList uses a doubly linked list structure ✔ ArrayList provides faster element access ✔ LinkedList provides faster insertion and deletion 📌 Key Takeaways ✔ Both ArrayList and LinkedList implement the List interface ✔ ArrayList is best for fast access and reading data ✔ LinkedList is better for frequent insertions and deletions ✔ Choosing the right data structure improves performance and efficiency Understanding these implementations helps developers select the most suitable data structure when working with collections in Java 💻⚡ Special thanks to Vaibhav Barde Sir for explaining these concepts clearly. #CoreJava #JavaLearning #ArrayList #LinkedList #JavaCollections #JavaDeveloper #Programming #LearningJourney
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development