Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Main {
    public static void main(String[] args) {
        List<Task> tasks = new LinkedList<Task>();
        String[] tasksLabels = new String[] { "A", "B", "C" };
        Clock clock = new Clock(tasksLabels.length, new Counter());
        for (String s : tasksLabels) {
            Task task = new Task(s, clock);
            tasks.add(task);
            task.start();
        }
    }
}

class Counter implements Runnable {
    volatile int step = 0;

    @Override
    public void run() {
        step++;
    }

    public int getStep() {
        return step;
    }
}

class Clock extends CyclicBarrier {
    Counter counter;

    public Clock(int parties, Counter counter) {
        super(parties, counter);
        this.counter = counter;
    }

    int getStep() {
        return counter.getStep();
    }
}

class Task extends Thread {
    String name;
    Clock clock;
    boolean running = true;
    Random random = new Random();

    Task(String name, Clock clock) {
        this.clock = clock;
        this.name = name;
    }

    boolean checkStep(int step) {
        return true;
    }

    @Override
    public void run() {
        while (running) {
            try {
                doIt(clock.getStep());
                clock.await();
            } catch (InterruptedException e) {
                running = false;
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                running = false;
                e.printStackTrace();
            }
        }
    }

    public void doIt(int step) throws InterruptedException {
        System.out.println(name + ": step " + step);
        // Simulate a busy task
        Thread.sleep(random.nextInt(1000));
    }
}