Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Thread Creation Methods

Tech May 18 2

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)

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.