Java Threads
Introduction to Threads
Threads allow a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the main program.
Creating a Thread
There are two ways to create a thread:
- By extending the
Threadclass and overriding itsrun()method:
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}- By implementing the
Runnableinterface:
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}Running Threads
If the class extends the Thread class, the thread can be started using start():
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}If the class implements Runnable, the thread is started by passing an instance to a Thread object:
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}Concurrency Problems
Since threads run simultaneously, execution order is unpredictable. This can cause concurrency problems when multiple threads modify shared data.
Example of concurrency issue:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
}
public void run() {
amount++;
}
}To avoid such issues, use isAlive() to check if a thread has finished execution:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
while(thread.isAlive()) {
System.out.println("Waiting...");
}
System.out.println("Main: " + amount);
amount++;
System.out.println("Main: " + amount);
}
public void run() {
amount++;
}
}