0% found this document useful (0 votes)
2 views2 pages

Threads in Java

This document provides an overview of threads in Java, describing them as lightweight processes that enable multithreading for improved performance. It outlines two primary ways to create threads: by extending the Thread class and by implementing the Runnable interface. Additionally, it explains the thread lifecycle and common methods such as start(), run(), sleep(), join(), and interrupt().

Uploaded by

quantumpulsecode
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Threads in Java

This document provides an overview of threads in Java, describing them as lightweight processes that enable multithreading for improved performance. It outlines two primary ways to create threads: by extending the Thread class and by implementing the Runnable interface. Additionally, it explains the thread lifecycle and common methods such as start(), run(), sleep(), join(), and interrupt().

Uploaded by

quantumpulsecode
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Threads in Java

Introduction

A thread in Java is a lightweight process. It is the smallest unit of execution in a program. Java supports

multithreading, allowing multiple threads to run concurrently, improving performance and responsiveness.

Ways to Create Threads

1. Extending the Thread class:

class MyThread extends Thread {

public void run() {

System.out.println("Thread running");

2. Implementing the Runnable interface:

class MyRunnable implements Runnable {

public void run() {

System.out.println("Runnable thread running");

Thread Lifecycle

1. New - Thread is created.

2. Runnable - Thread is ready to run.

3. Running - Thread is executing.

4. Waiting/Blocked - Thread is waiting for a resource.

5. Terminated - Thread has finished execution.

Common Thread Methods

start() - Starts the thread.

run() - Contains the code to be executed.


Threads in Java

sleep(ms) - Pauses thread for specified time.

join() - Waits for thread to finish.

interrupt() - Interrupts the thread.

Example

class MyThread extends Thread {

public void run() {

for(int i=1; i<=5; i++) {

try { Thread.sleep(500); } catch(Exception e) {}

System.out.println(i);

public static void main(String args[]) {

MyThread t1 = new MyThread();

t1.start();

You might also like