Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
        List<Particle> allTheParticles = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            allTheParticles.add(new Particle(i, allTheParticles));
        }
        while (true) {
            executor.invokeAll(allTheParticles);
            executor.invokeAll(allTheParticles);
        }
    }
}

class Particle implements Callable<Void> {
    int id;
    int calculatedForce;
    State particleState = State.Update;
    List<Particle> allTheParticles;

    public Particle(int id, List<Particle> allTheParticles) {
        this.id = id;
        this.allTheParticles = allTheParticles;
    }

    private void calculateNetForce() {
        System.out.println("calculation in " + id);
        String someIntenseOperation = "";
        for (int i = 0; i < 10000; i++) {
            someIntenseOperation += allTheParticles.size();
        }
        System.out.println("someIntenseOperation:" + someIntenseOperation);
        calculatedForce = 0;
        particleState = State.Calculate;
    }

    private void updatePosition() {
        System.out.println("updating position of " + id);
        particleState = State.Update;
    }

    @Override
    public Void call() throws Exception {
        switch (particleState) {
        case Calculate:
            updatePosition();
            break;
        case Update:
            calculateNetForce();
            break;
        }
        return null;
    }
}

enum State {
    Update, Calculate
}