Thread / Runnable

2

I would like to know how to perform some action every 10 seconds, specifically call from main to my method msj() every 10 seconds using the class Thread and I would also like to know how it would be done using the interface Runnable .

package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {
    }

    public void msj() {
        System.out.println("hola");
    }
}
    
asked by Abner 27.03.2017 в 21:42
source

4 answers

2

I recommend you read a bit of the Thread class, see and make examples to adapt performance according to your needs, answering your question, the recommended way to call a method every x time, from Java 5 is with a ScheduledExecutorService , create it using the class Executors .

public class RunClass {
    final Runnable tarea = new Runnable() {
        public void run() {
            hola_mundo();
        }
    };

    public static void main(String[] args) {

        RunClass on = new RunClass();
        ScheduledExecutorService timer = Executors
                .newSingleThreadScheduledExecutor();
        timer.scheduleAtFixedRate(on.tarea, 1, 10, TimeUnit.SECONDS);
    }

    void hola_mundo() {
        System.out.println("Hola Mundo");
    }
}

Documentation:

ScheduledExecutorService

    
answered by 27.03.2017 в 22:06
1

The use of an interface object ScheduledExecutorService is definitely the way to go ... but if this is a merely didactic exercise, then:

java.lang.Thread

A solution using only the class java.lang.Thread could be similar to the following:

public static void main(String[] args) {
    while (true) {
        new Thread() {
            @Override
            public void run() {
                msj();
            }
        }.start();
        try {
            Thread.sleep(10_000);
        } catch (InterruptedException e) {
            System.err.println(e);
        }
    }
}

public static void msj() {
    System.out.println("hola");
}

java.lang.Runnable

The thing changes with java.lang.Runnable , because there is no a solution that uses only that class, since it is required that something execute the task. For example, with java.lang.Thread :

public static void main(String[] args) {
    while (true) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                msj();
            }
        }).start();
        try {
            Thread.sleep(10_000);
        } catch (InterruptedException e) {
            System.err.println(e);
        }
    }
}

public static void msj() {
    System.out.println("hola");
}
    
answered by 28.03.2017 в 00:31
0
package javaapplication1;


   public class JavaApplication1 extends Thread {


    public static void main(String[] args) {
    JavaApplication1 hilo= new JavaApplication1 ();
     hilo.start();
    }

    public void run(){
    while(true  ){
    try{
    msj();
    Thread.sleep(10000);
    }catch( InterruptedException e){}

    }
    }

   public void msj()
    {
        System.out.println("hola");
    }

    }
    
answered by 27.03.2017 в 22:48
0

Hello try the following code snippet:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class JavaApplication1 
{

public static void main(String[] args) 
{
    tareaProgramada();
}

public static void msj()
{
    System.out.println("hola");
}

public static void tareaProgramada()
{
    //Debemos obtener una instancia de la Interfaz ScheduledExecutorService
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    //luego debemos crear una instancia de la interfaz Runnable, tambien puede ser Callable en la cual indicamos el metodo que vamos a ejecutar
    Runnable tarea = () -> msj();
    //finalmente ordenamos ejecutar la tarea programada con un intervalo llamando al metodo scheduleWithFixedDelay el cual recibe una instancia de Runnable o Callable
    //ademas de dos int , el primero especificando cuanto tiempo esperar para ejecutar la primera tarea ,el segundo el intervalo que se esperara para continuar la siguiente ejecucion
    //el ultimo parametro es un TimeUnit el cual especifica la unidad tiempo con la que se trabajara
    service.scheduleWithFixedDelay(tarea, 0, 5, TimeUnit.SECONDS);

 }
}

Documentation of the Java Concurrency API: link

    
answered by 28.03.2017 в 00:46