VademécumVademécum\Thread [hilo] (concepto)Thread [hilo] (concepto)\¿Cómo se crea un thread? Opción 1: new Thread(Runnable)

¿Cómo se crea un thread? Opción 1: new Thread(Runnable)

 

class Repeater

public class Repeater implements Runnable {

      private String id;

      private int count;

 

      public Repeater(String id, int count) {

            this.id = id;

            this.count = count;

      }

 

      public void run() {

            do {

                  System.out.println(id + ": " + count);

                  count--;

                  try {

                        Thread.sleep(1000); // 1000ms = 1s

                  } catch (InterruptedException ignore) {

                  }

            } while (count > 0);

            System.out.println(id + ": end");

      }

}    

 

Una vez dispone de objetos que implementan la interfaz Runnable, cree el Thread:

      Runnable repeater = new Repeater(id, count);

      Thread thread = new Thread(repeater);                   

 

principio