Java Thread Creation Methods
Java Multithreading
Method 1: Extending Thread Class
Too create a thread by extending the Thread class, override the run() method and call start() to begin execution.
public class CustomThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("Executing thread task: " + i);
}
}
public static void main(String[] args) {
CustomThread thread = new CustomThread();
thread.start();
for (int i = 0; i < 200; i++) {
System.out.println("Main thread executing: " + i);
}
}
}
Calling start() creates a new thread alongside the main thread. Directly calling run() executes in the main thread only.
Example: Image Downloader
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class DownloadThread extends Thread {
private String fileUrl;
private String fileName;
public DownloadThread(String fileUrl, String fileName) {
this.fileUrl = fileUrl;
this.fileName = fileName;
}
@Override
public void run() {
FileDownloader downloader = new FileDownloader();
downloader.download(fileUrl, fileName);
}
public static void main(String[] args) {
new DownloadThread("https://example.com/image1.jpg", "1.jpg").start();
new DownloadThread("https://example.com/image2.jpg", "2.jpg").start();
}
}
class FileDownloader {
public void download(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
System.out.println(name + " downloaded successfully");
} catch (IOException e) {
System.out.println("Download failed");
}
}
}
Method 2: Implementing Runnable Interface
public class RunnableExample implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("Runnable thread: " + i);
}
}
public static void main(String[] args) {
RunnableExample example = new RunnableExample();
new Thread(example).start();
}
}
Concurrency Issues
When multiple threads access shared resources:
public class TicketSystem implements Runnable {
private int tickets = 10;
@Override
public void run() {
while (tickets > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " purchased ticket " + tickets--);
}
}
public static void main(String[] args) {
TicketSystem system = new TicketSystem();
new Thread(system, "Customer 1").start();
new Thread(system, "Customer 2").start();
}
}
Method 3: Implementing Callable Interface
(Implementation example omitted for brevity)