Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Thread Class

Java Thread Class

The Thread class is the core class in Java for creating and managing threads.

In Java, every thread is an instance of the Thread class. A thread can be understood as an independently executed "subtask" within a program, allowing the program to perform multiple operations simultaneously.

There are two ways to create threads in Java:

  1. Extend the Thread class
  2. Implement the Runnable interface

Basic Usage of the Thread Class

Create a thread

Example

// Approach 1: Extend the Thread class

class

MyThread

extends

Thread

{

   

public

void

run

(

)

{

       

System

.

out

.

println

(

"The thread is running"

)

;

   

}

}

// Approach 2: Implement the Runnable interface

class

MyRunnable

implements

Runnable

{

   

public

void

run

(

)

{

       

System

.

out

.

println

(

"The thread is running"

)

;

   

}

}

public

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Using the inheritance approach

        MyThread thread1

=

new

MyThread

(

)

;

        thread1.

start

(

)

;

       

       

// Using the interface approach

       

Thread

thread2

=

new

Thread

(

new

MyRunnable

(

)

)

;

        thread2.

start

(

)

;

   

}

}

Thread Lifecycle

A Java thread has the following states:


Common Methods of the Thread Class

Basic Control Methods

Example

Thread

thread

=

new

Thread

(

(

)

->

{

   

System

.

out

.

println

(

"Thread executing"

)

;

}

)

;

thread.

start

(

)

;

 

// Start the thread

thread.

join

(

)

;

 

// Wait for the thread to finish

thread.

sleep

(

1000

)

;

// Sleep the thread for 1 second

Thread Priority

Example

thread.

setPriority

(

Thread

.

MAX_PRIORITY

)

;

 

// Highest priority (10)

thread.

setPriority

(

Thread

.

NORM_PRIORITY

)

;

// Default priority (5)

thread.

setPriority

(

Thread

.

MIN_PRIORITY

)

;

 

// Lowest priority (1)

Thread Interruption

Example

thread.

interrupt

(

)

;

// Interrupt the thread

// Check the interrupt status in the thread

if

(

Thread

.

interrupted

(

)

)

{

   

// Handle interrupt logic

}


Thread synchronization

When multiple threads access shared resources, synchronization mechanisms are needed to avoid data inconsistency.

Using the synchronized keyword

Example

class

Counter

{

   

private

int

count

=

0

;

   

   

public

synchronized

void

increment

(

)

{

        count

++;

   

}

}

Using the Lock interface

Example

import

java.util.concurrent.locks.Lock

;

import

java.util.concurrent.locks.ReentrantLock

;

class

Counter

{

   

private

int

count

=

0

;

   

private

Lock lock

=

new

ReentrantLock

(

)

;

   

   

public

void

increment

(

)

{

        lock.

lock

(

)

;

       

try

{

            count

++;

       

}

finally

{

            lock.

unlock

(

)

;

       

}

   

}

}


Thread Pools and the Thread Class

In actual development, thread pools are usually used to manage threads rather than creating Thread objects directly.

Example

import

java.util.concurrent.ExecutorService

;

import

java.util.concurrent.Executors

;

public

class

ThreadPoolExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        ExecutorService executor

=

Executors.

newFixedThreadPool

(

5

)

;

       

       

for

(

int

i

=

0

;

i

<

10

;

i

++

)

{

            executor.

execute

(

(

)

->

{

               

System

.

out

.

println

(

"The thread executes the task"

)

;

           

}

)

;

       

}

       

        executor.

shutdown

(

)

;

   

}

}


Best Practices

  1. Prefer creating threads by implementing the Runnable interface
  2. Use a thread pool to manage thread resources
  3. Avoid excessive synchronization; use synchronization only when necessary
  4. Use the volatile keyword to ensure variable visibility
  5. Consider using the advanced utility classes in the Java concurrency package (java.util.concurrent)

By using the Thread class and related concurrency utilities appropriately, you can write efficient and reliable multithreaded Java programs.