Introduction
Java provides built-in support for multithreading through the Thread
class, which allows developers to execute multiple tasks concurrently. Understanding the Thread
class and its methods is essential for efficient and scalable Java applications.
In this article, we will explore the Thread
class, its important methods, and practical examples to help Java professionals master multithreading.
What is the Thread Class in Java?
The Thread
class in Java belongs to the java.lang
package and is used to create and manage threads. It extends the Object
class and implements the Runnable
interface, allowing developers to define and execute independent execution paths.
Creating a Thread in Java
There are two main ways to create a thread in Java:
- Extending the
Thread
class - Implementing the
Runnable
interface
1. Extending the Thread
Class
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();
}
}
2. Implementing the Runnable
Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
Important Methods of the Thread Class
1. start()
This method starts the execution of the thread by calling the run()
method.
Thread t = new Thread(new MyRunnable());
t.start();
2. run()
Defines the code that constitutes the thread’s task. It must be overridden in a subclass.
3. sleep(long milliseconds)
Pauses the thread for a specified time.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
4. join()
Makes the current thread wait until the specified thread finishes execution.
Thread t1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1 - " + i);
}
});
t1.start();
t1.join();
5. isAlive()
Checks whether a thread is still running.
if (t1.isAlive()) {
System.out.println("Thread is still running");
}
6. yield()
Pauses the current thread and allows other threads of the same priority to execute.
Thread.yield();
7. setName(String name)
and getName()
Sets and retrieves the name of a thread.
Thread t = new Thread();
t.setName("MyThread");
System.out.println(t.getName());
8. setPriority(int priority)
and getPriority()
Sets and retrieves the priority of a thread.
t.setPriority(Thread.MAX_PRIORITY);
System.out.println(t.getPriority());
9. interrupt()
Interrupts a sleeping or waiting thread.
t.interrupt();
10. daemonThread()
Marks a thread as a daemon thread.
t.setDaemon(true);
Practical Example of Multithreading
class MultiThreadDemo extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
}
}
public static void main(String[] args) {
MultiThreadDemo t1 = new MultiThreadDemo();
MultiThreadDemo t2 = new MultiThreadDemo();
t1.setName("Thread 1");
t2.setName("Thread 2");
t1.start();
t2.start();
}
}
External Links
FAQs
1. What is the difference between start()
and run()
methods in Java?
The start()
method creates a new thread and invokes the run()
method, whereas calling run()
directly executes the code in the main thread.
2. Can we start a thread twice in Java?
No, once a thread has been started, it cannot be restarted.
3. What is the purpose of the yield()
method?
yield()
allows other threads of the same priority to execute before resuming.
4. What happens if the run()
method is not overridden?
The default implementation of run()
does nothing, and the thread will not execute any task.
5. What is a daemon thread?
Daemon threads run in the background and do not prevent the JVM from exiting.
6. How do you stop a running thread in Java?
The interrupt()
method is used to request a thread to stop.
7. How does sleep()
differ from wait()
?
sleep()
pauses the thread for a specified time, while wait()
makes a thread wait until notified.
8. What is thread priority in Java?
Thread priority determines the execution preference of threads but does not guarantee execution order.
9. Can multiple threads run concurrently in Java?
Yes, Java supports multithreading to run multiple tasks in parallel.
10. What is the difference between synchronized
and volatile
?
synchronized
ensures mutual exclusion, while volatile
guarantees visibility of changes across threads.
Mastering the Thread
class and its methods is crucial for Java professionals working on concurrent programming. By leveraging these features, developers can create efficient, responsive, and scalable applications.