public class BerbagiHeap {
    public static void main(String[] args) throws InterruptedException {
        // Satu objek array di heap; semua thread di proses yang sama melihatnya.
        int[] hasil = new int[3];
        String[] rentang = {"1-100", "101-200", "201-300"};

        Thread[] pekerja = new Thread[3];
        for (int i = 0; i < pekerja.length; i++) {
            int indeks = i; // variabel efektif final agar bisa dipakai lambda
            pekerja[i] = new Thread(() -> {
                int jumlah = 0; // variabel lokal: hidup di stack thread ini
                int awal = indeks * 100 + 1;
                int akhir = (indeks + 1) * 100;
                for (int n = awal; n <= akhir; n++) {
                    jumlah += n;
                }
                hasil[indeks] = jumlah; // menulis ke objek bersama di heap
            });
            pekerja[i].setName("pekerja-" + (i + 1));
            pekerja[i].start();
        }

        for (Thread t : pekerja) {
            t.join();
        }

        // Dicetak setelah semua join sehingga urutan keluaran pasti tetap.
        for (int i = 0; i < hasil.length; i++) {
            System.out.println(pekerja[i].getName() + " menjumlahkan "
                    + rentang[i] + ": " + hasil[i]);
        }
    }
}
