import java.util.concurrent.Semaphore;

public class ThreadStopTtsp {
    static int NUM_THREADS = 10_000;
    static Semaphore s = new Semaphore(0);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            // Start a bunch of threads which will all exit when they acquire a token
            startThreads();
            System.out.println("Threads started.");
            // Trigger threads to exit
            s.release(NUM_THREADS);
            while (s.availablePermits() != 0) { }
            System.out.println("Threads finished. Triggering GC.");
            System.gc();
            Thread.sleep(1000);
        }
    }

    static void startThreads() {
        for (int i = 0; i < NUM_THREADS; i++) {
            new Thread(() -> {
                try { s.acquire(); } catch (Exception e) { throw new RuntimeException(e); }
            }).start();
        }
    }
}
