The use of an interface object ScheduledExecutorService
is definitely the way to go ... but if this is a merely didactic exercise, then:
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");
}
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");
}