Thread Class Methods in Java with Examples

Introduction

The Thread class in Java provides various methods for creating, controlling, and managing threads. These methods enable the manipulation of thread behavior, such as starting, stopping, pausing, and resuming threads. Understanding these methods is essential for effective multithreading in Java.

Table of Contents

  1. Overview of Thread Class Methods
  2. Methods for Thread Control
    • start()
    • run()
    • sleep(long millis)
    • interrupt()
    • join()
    • isAlive()
  3. Methods for Thread Information
    • getName()
    • setName(String name)
    • getId()
    • getPriority()
    • setPriority(int priority)
    • getState()
  4. Deprecated Methods
    • stop()
    • suspend()
    • resume()
  5. Example: Using Thread Methods
  6. Conclusion

1. Overview of Thread Class Methods

The Thread class provides a comprehensive set of methods to control and manage threads. These methods can be categorized into methods for thread control, thread information, and deprecated methods.

2. Methods for Thread Control

start()

Starts the execution of the thread. The Java Virtual Machine (JVM) calls the run() method of this thread.

Example:

public class StartExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        thread.start();
    }
}

run()

If a thread was constructed using a separate Runnable object, then that Runnable object's run() method is called; otherwise, this method does nothing and returns.

Example:

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable is running.");
    }
}

public class RunExample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

sleep(long millis)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

Example:

public class SleepExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000); // Sleep for 1 second
                System.out.println("Thread woke up after 1 second.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}

interrupt()

Interrupts a thread that is in the sleeping, waiting, or blocked state.

Example:

public class InterruptExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Thread was interrupted.");
            }
        });
        thread.start();
        thread.interrupt();
    }
}

join()

Waits for the thread to die.

Example:

public class JoinExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        thread.start();
        try {
            thread.join();
            System.out.println("Thread has finished.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

isAlive()

Tests if the thread is alive.

Example:

public class IsAliveExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        thread.start();
        System.out.println("Is thread alive? " + thread.isAlive());
    }
}

3. Methods for Thread Information

getName()

Returns the name of the thread.

Example:

public class GetNameExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        System.out.println("Thread name: " + thread.getName());
        thread.start();
    }
}

setName(String name)

Changes the name of the thread.

Example:

public class SetNameExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        thread.setName("MyThread");
        System.out.println("Thread name: " + thread.getName());
        thread.start();
    }
}

getId()

Returns the thread's ID.

Example:

public class GetIdExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        System.out.println("Thread ID: " + thread.getId());
        thread.start();
    }
}

getPriority()

Returns the priority of the thread.

Example:

public class GetPriorityExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        System.out.println("Thread priority: " + thread.getPriority());
        thread.start();
    }
}

setPriority(int priority)

Changes the priority of the thread.

Example:

public class SetPriorityExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        thread.setPriority(Thread.MAX_PRIORITY);
        System.out.println("Thread priority: " + thread.getPriority());
        thread.start();
    }
}

getState()

Returns the state of the thread.

Example:

public class GetStateExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running.");
        });
        System.out.println("Thread state: " + thread.getState());
        thread.start();
    }
}

4. Deprecated Methods

stop()

The stop() method is deprecated because it is inherently unsafe. It forces a thread to terminate without giving it a chance to release resources, potentially causing data corruption.

Example:

public class StopExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("Thread is running.");
            }
        });
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.stop(); // Not recommended
    }
}

suspend() and resume()

The suspend() and resume() methods are deprecated because they can cause deadlocks. They suspend a thread and resume it, respectively.

Example:

public class SuspendResumeExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("Thread is running.");
            }
        });
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.suspend(); // Not recommended
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.resume(); // Not recommended
    }
}

5. Example: Using Thread Methods

Let's create a complete example that demonstrates the use of various Thread methods.

Example:

public class ThreadMethodsExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " is running. Count: " + i);
                try {
                    Thread.sleep(1000); // Sleep for 1 second
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " was interrupted.");
                }
            }
        }, "MyThread");

        thread.setPriority(Thread.MAX_PRIORITY);
        System.out.println("Thread ID: " + thread.getId());
        System.out.println("Thread Name: " + thread.getName());
        System.out.println("Thread Priority: " + thread.getPriority());
        System.out.println("Thread State before start: " + thread.getState());

        thread.start();

        System.out.println("Thread State after start: " + thread.getState());

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread State after completion: " + thread.getState());
    }
}

Output:

Thread ID: 10
Thread Name: MyThread
Thread Priority: 10
Thread State before start: NEW
Thread State after start: RUNNABLE
MyThread is running. Count: 0
MyThread is running. Count: 1
MyThread is running. Count: 2
MyThread is running. Count: 3
MyThread is running. Count: 4
Thread State after completion: TERMINATED

Explanation:

  • The Thread object is created with a name "MyThread" and its priority is set to MAX_PRIORITY.
  • Various thread information methods (getId(), getName(), getPriority(), and getState()) are used to print thread details.
  • The start() method is called to begin thread execution.
  • The join() method is used to wait for the thread to complete.
  • The thread state is printed before start, after start, and after completion.

6. Conclusion

The Thread class in Java provides a rich set of methods to control and manage threads. Understanding these methods is crucial for effective multithreading and synchronization in Java applications. While some methods are deprecated due to safety concerns, the remaining methods offer powerful capabilities for thread management.

Happy coding!

Comments