Thread.sleep() blocca il thread in cui si trova per un tot di millisecondi
codice:
Thread t = new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 ha finito");
});
t.setDaemon(false);
t.start();
System.out.println("Thread 1 ha finito");
codice:
Thread t = new Thread(() -> System.out.println("Thread 2 ha finito"));
t.setDaemon(false);
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 ha finito");
Nel primo esempio finirà prima il thread in esecuzione mentre nel secondo quello creato, puoi utilizzare Thread.sleep() anche senza creare nessun thread fermando il thread principale.