Sobes.tech
Junior — Middle

How to implement thread management through an interface in your application?

sobes.tech AI

Answer from AI

To manage threads through an interface in Java, you can define an interface with methods for starting, stopping, and checking the thread's status. Then, implement this interface in classes that encapsulate the thread logic.

Example:

public interface ThreadController {
    void startThread();
    void stopThread();
    boolean isRunning();
}

public class MyThread implements ThreadController, Runnable {
    private Thread thread;
    private volatile boolean running = false;

    @Override
    public void startThread() {
        if (thread == null || !thread.isAlive()) {
            running = true;
            thread = new Thread(this);
            thread.start();
        }
    }

    @Override
    public void stopThread() {
        running = false;
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public void run() {
        while (running) {
            // thread logic
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

This approach allows abstracting thread management and using different implementations through a single interface.