Munir
Munir

Reputation: 11

How to cancel all threads after 5 seconds from the main thread with shared memory (shared variable)?

My code:

public class Task3 {
    public static void main(String[] args) throws InterruptedException {
    
    ExecutorService poolOfThreads = Executors.newFixedThreadPool(10);
    long start = System.currentTimeMillis();
    for (int i = 1; i <= 10; i++) {
        int finalI = i;
        poolOfThreads.submit(new Task2Thread(i, start));
    }

    poolOfThreads.shutdown();
    Thread.sleep(5000);

    poolOfThreads.awaitTermination(1, TimeUnit.DAYS);
}
}


public class Task3Thread implements Runnable{
    
volatile boolean running = true;
private int id;
private long time;

public Task3Thread(int id, long time) {
    this.id = id;
    this.time = time;
}

@Override
public void run() {
    while (running) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("Thread: " + id + ", time: " + (end - time));
    }
}

public void setRunning(boolean running) {
    this.running = running;
}
}

These classes spawn 10 threads, each of which every second prints to the console its number and the time elapsed since its launch in milliseconds.

Now I need to cancel all threads after 5 seconds from the main thread with shared memory (shared variable).

How to do it? Tell me please

Upvotes: 1

Views: 172

Answers (1)

Melroy Dsouza
Melroy Dsouza

Reputation: 196

You can try something like this - store the thread references in an array and after 5 seconds you can fetch the threads one by one from the array and set the running volatile flag to false. Please check the below modified main method:

Modified code:

public class Task3 {

public static void main(String[] args) throws InterruptedException {
    int threadPoolSize = 10;

    Task3Thread[] threads = new Task3Thread[threadPoolSize];

    ExecutorService poolOfThreads = Executors.newFixedThreadPool(threadPoolSize);
    long start = System.currentTimeMillis();
    for (int i = 1; i <= 10; i++) {
        int finalI = i;
        Task3Thread task3Thread = new Task3Thread(i, start);
        threads[i-1] = task3Thread;
        poolOfThreads.submit(task3Thread);
    }


    poolOfThreads.shutdown();
    Thread.sleep(5000);

    for (Task3Thread thread : threads)
    {
        thread.setRunning(false);
    }
}

}

Upvotes: 1

Related Questions