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
question from:
https://stackoverflow.com/questions/65856927/how-to-cancel-all-threads-after-5-seconds-from-the-main-thread-with-shared-memor 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…