Java Programming — Study Notes

Unit 04

Threads & Packages in Java

4 Questions 6 Marks Each Java
01
6 Marks Question

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

Key Features
  • 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 Thread class
  • By implementing the Runnable interface

Example — Using Thread Class

Java Code
class 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
    }
}
Output Thread is running...

Explanation

  • A class MyThread extends the Thread class.
  • The run() method defines the task to be executed.
  • The start() method creates a new thread and calls run() internally.
Conclusion Threads are essential for performing multiple tasks simultaneously in Java applications. They improve performance, responsiveness, and efficient resource utilization.
02
6 Marks Question

Thread Lifecycle and Thread Priority

Part 1 — Thread Life Cycle

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

1
New State
Thread is created using the new keyword but not yet started.
Example: Thread t = new Thread();
2
Runnable State
Thread enters this state after calling start(). It is ready to run but waiting for CPU scheduling.
3
Running State
Thread scheduler selects the thread and it starts execution. The run() method executes in this state.
4
Non-Runnable (Blocked / Waiting) State
Thread is temporarily inactive — waiting for resources, I/O operations, or another thread. Methods like sleep(), wait(), join() cause this state.
5
Terminated (Dead) State
Thread finishes execution of the run() method. It cannot be restarted.
Summary Flow: New → Runnable → Running → (Blocked if needed) → Terminated
Part 2 — Thread Priority

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

1
MIN_PRIORITY
Lowest priority
5
NORM_PRIORITY
Default priority
10
MAX_PRIORITY
Highest priority
Higher priority threads are more likely to execute first, but it is not guaranteed — it depends on the JVM scheduler.

Methods for Thread Priority

getPriority()Returns the current thread priority
setPriority(int p)Sets the thread priority

Example

Java Code
class 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 t1 has priority 8, t2 has priority 3.
  • Thread with higher priority (t1) is more likely to execute first.
Conclusion The thread life cycle defines the stages of thread execution, while thread priority helps the scheduler decide execution order. Both are essential for efficient multithreading in Java.
03
6 Marks Question

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

Built-in Packages

Provided by the Java API. Ready to use without any creation.

  • java.lang
  • java.util
  • java.io
  • java.awt
User-defined Packages

Created by programmers using the package keyword to organise their own classes.

Advantages of Packages

Advantages
  • 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:

Syntax
package 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.
Importing Packages (Type Imports)

The import statement is used to access classes from other packages.

import pkg.* Importing Entire Package

Imports all classes from the specified package.

Syntax
import package_name.*;
import pkg.Class Importing Specific Class

Imports only a particular class from the package.

Syntax
import package_name.class_name;

Example Program

Java Code
package 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

  • package defines the package name for this file.
  • import java.util.* imports all classes from java.util.
  • import java.util.Scanner imports only the Scanner class.
Conclusion Packages help organise Java programs efficiently, while proper naming and import statements allow easy access and reuse of classes across different programs.
04
6 Marks Question

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

1
Declare the Package
A package is declared at the very beginning of the Java source file.
package package_name;
2
Define Public Class
Classes inside the package should be declared as public if they need to be accessed from other packages.
3
Create Directory Structure
A folder must be created with the same name as the package. Java is case-sensitive, so names must match exactly.
4
Store the File in Package Directory
The .java source file must be placed inside the created directory folder.
5
Compile the Program
After compilation, the .class file is generated inside the package folder.
6
Run the Program
The program is executed using the package name followed by the class name.
java package_name.class_name

Example

Java Code
package pack;

public class A {
    public void msg() {
        System.out.println("Hello");
    }
}
Output Hello
  • The file is saved inside a folder named pack.
  • The class A is public so it can be accessed from other packages.
  • To run: java pack.A
Conclusion Package specification helps in organising Java programs into structured directories, making code management, reusability, and access control easier.