YouTip LogoYouTip

Java Thread Class

Thread class is the core class in Java for creating and managing threads. In Java, each thread is an instance of the Thread class. A thread can be understood as an independently executing "subtask" in a program, which allows the program to execute multiple operations simultaneously. There are two ways to create threads in Java: 1. By extending the Thread class 2. By implementing the Runnable interface * * * ## Basic Usage of Thread Class ### Creating Threads ## Example // Method 1: Extend Thread class class MyThread extends Thread{ public void run(){ System.out.println("Thread is running"); } } // Method 2: Implement Runnable interface class MyRunnable implements Runnable{ public void run(){ System.out.println("Thread is running"); } } public class Main { public static void main(String[] args){ // Using inheritance MyThread thread1 =new MyThread(); thread1.start(); // Using interface Thread thread2 =new Thread(new MyRunnable()); thread2.start(); } } ### Thread Lifecycle A Java thread can be in the following states: * **NEW**: A newly created thread that hasn't called start() yet * **RUNNABLE**: Runnable state, may be running or waiting for CPU time * **BLOCKED**: Thread is blocked, waiting to acquire a monitor lock * **WAITING**: Waiting state, waiting for another thread to perform a specific operation * **TIMED_WAITING**: Waiting state with a time limit * **TERMINATED**: Thread has terminated * * * ## Common Methods of Thread Class ### Basic Control Methods ## Example Thread thread =new Thread(()->{ System.out.println("Thread executing"); }); thread.start();// Start thread thread.join();// Wait for thread to finish thread.sleep(1000);// Thread sleeps for 1 second ### Thread Priority ## Example thread.setPriority(Thread.MAX_PRIORITY);// Max priority (10) thread.setPriority(Thread.NORM_PRIORITY);// Default priority (5) thread.setPriority(Thread.MIN_PRIORITY);// Min priority (1) ### Thread Interruption ## Example thread.interrupt();// Interrupt thread // Check interrupt status in thread if(Thread.interrupted()){ // Handle interrupt logic } * * * ## Thread Synchronization When multiple threads access shared resources, synchronization mechanisms need to be used to avoid data inconsistency issues. ### Using synchronized Keyword ## Example class Counter { private int count =0; public synchronized void increment(){ count++; } } ### Using 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 Pool and Thread Class In actual development, thread pools are usually used to manage threads instead of directly creating Thread objects. ## 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 { System.out.println("Thread executing task"); }); } executor.shutdown(); } } * * * ## Best Practices 1. Prefer using the method of implementing Runnable interface to create threads 2. Use thread pools to manage thread resources 3. Avoid over-synchronization, only use synchronization mechanisms when necessary 4. Use volatile keyword to ensure variable visibility 5. Consider using advanced utility classes from Java concurrency package (java.util.concurrent) By using the Thread class and related concurrency tools reasonably, you can write efficient and reliable multi-threaded Java programs.
← Java Url ClassJava Inputstream Class β†’