Threads in Java
Introduction
A thread in Java is a lightweight subprocess and the smallest unit of execution. It represents a separate path of execution within a program. Threads run inside a process and share the same memory space.
Definition: A thread is an independent flow of control that allows multiple tasks to be executed simultaneously within a single program.
Key Features of Threads
- Threads are lightweight and faster than processes.
- Multiple threads share the same memory area.
- Threads are independent — an exception in one does not affect others.
- They enable multitasking and efficient CPU utilization.
- Context switching between threads is faster than between processes.
Creation of Threads in Java
Threads can be created in two ways:
- By extending the
Threadclass - By implementing the
Runnableinterface
Example — Using Thread Class
Java Codeclass MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String args[]) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread
}
}
Explanation
- A class
MyThreadextends theThreadclass. - The
run()method defines the task to be executed. - The
start()method creates a new thread and callsrun()internally.
Thread Lifecycle and Thread Priority
The life cycle of a thread represents the different states a thread passes through during its execution. It is controlled by the JVM.
States of a Thread
new keyword but not yet started.Example:
Thread t = new Thread();start(). It is ready to run but waiting for CPU scheduling.run() method executes in this state.sleep(), wait(), join() cause this state.run() method. It cannot be restarted.Thread priority determines the order in which threads are scheduled for execution by the CPU. Each thread has a priority value between 1 to 10.
Priority Constants
Methods for Thread Priority
getPriority()Returns the current thread prioritysetPriority(int p)Sets the thread priorityExample
Java Codeclass MyThread extends Thread {
public void run() {
System.out.println("Running: " + Thread.currentThread().getName());
}
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setPriority(8);
t2.setPriority(3);
t1.start();
t2.start();
}
}
Explanation
- Two threads are created with different priorities.
- Thread
t1has priority 8,t2has priority 3. - Thread with higher priority (
t1) is more likely to execute first.
Packages in Java — Naming and Type Imports
Introduction to Packages
A package in Java is a collection of related classes, interfaces, and sub-packages. It acts as a container to organise code into a hierarchical structure.
Definition: A package is a namespace that organises a set of related classes and interfaces.
Types of Packages
Provided by the Java API. Ready to use without any creation.
java.langjava.utiljava.iojava.awt
Created by programmers using the package keyword to organise their own classes.
Advantages of Packages
- Helps in code organisation and management
- Avoids naming conflicts between classes
- Provides access protection (encapsulation)
- Promotes code reusability
Package Naming
A package is declared at the beginning of a Java file using:
Syntaxpackage package_name;
Naming Conventions
- Usually written in lowercase letters.
- Should match the directory structure exactly.
- Can be hierarchical — e.g.,
com.example.project - Java is case-sensitive, so package name must match folder name exactly.
The import statement is used to access classes from other packages.
Imports all classes from the specified package.
Syntaximport package_name.*;
Imports only a particular class from the package.
Syntaximport package_name.class_name;
Example Program
Java Codepackage mypack;
import java.util.*; // import entire package
import java.util.Scanner; // import specific class
class Test {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number:");
int n = sc.nextInt();
System.out.println(n);
}
}
Explanation
packagedefines the package name for this file.import java.util.*imports all classes fromjava.util.import java.util.Scannerimports only theScannerclass.
Package Specification in Java
Introduction
Package specification in Java refers to the process of declaring, defining, and organising a package so that classes and interfaces can be grouped and used efficiently.
Steps for Package Specification
package package_name;
public if they need to be accessed from other packages..java source file must be placed inside the created directory folder..class file is generated inside the package folder.java package_name.class_name
Example
Java Codepackage pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
- The file is saved inside a folder named
pack. - The class
Aispublicso it can be accessed from other packages. - To run:
java pack.A