Life time of an object [closed]

1

I need to do a program with java that creates an object every 30 seconds and puts it in a queue and then does some operations with them. I had thought about creating the object and that creating it would also create a kind of counter, so that when it reaches 30 seconds, another object is created until you have 100.

I tried something with System.currentTimeMillis (); but I can not think of how to make it count for 30 seconds and then do other operations.

I've been looking and I've tried this:

Timer timer = new Timer();
TimerTask task = new TimerTask() {

            @Override
            public void run() {
                do {
                Camion c = new Camion();
                A.add(c);
                System.out.println(c.toString());
                }while(A.size()<100);
            }
        };

        timer.schedule(task, 30000);

But it's not what I wanted, this does it all at once at 30 seconds.

    
asked by Isma 23.10.2018 в 16:36
source

1 answer

0

I can think of a way to do this with static classes.

As mentioned by @OscarGarcia, the standard way to achieve fixed delays is with a ScheduledExecutorService :

private static ScheduledExecutorService servicio = new ScheduledThreadPoolExecutor(1);

Besides this, if you want to cancel the program after 100 attempts you will need a ScheduledFuture :

private static ScheduledFuture<?> futuro;

Once you have this, it is as simple as defining an extra variable in your Runnable that keeps a count of times it has been executed:

private static class CrearCamion implements Runnable {

    private int ejecuciones = 1;

    @Override
    public void run() {
        if(++ejecuciones > 100) {
            futuro.cancel(false); // cancelamos si llevamos más de 100
        } else {
            Camion c = new Camion();
            A.add(c);
            System.out.println(c.toString());
        }
    }
}

And finally, in your main() , be sure to assign the ScheduledFuture to the result of the call to scheduleAtFixedRate :

public static void main(String[] args) throws Exception {
    // el tercer y el cuarto argumento determinan el tiempo de espera entre ejecuciones
    futuro = servicio.scheduleAtFixedRate(new CrearCamion(), 0, 30, TimeUnit.SECONDS);
}

Try it:)

    
answered by 24.10.2018 в 10:29