public class Test {
public static void main(String...args) {
// Methode 1
Thread t = new Thread(new MyRunnable1(new Player()));
t.start();
// Methode 2
t = new Thread(new MyRunnable2());
t.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
}
}
class Player {
int hp = 100;
public void punch() {
hp -= 50;
}
}
class MyRunnable1 implements Runnable {
private Player p;
public MyRunnable1(Player p) {
this.p = p;
}
@Override
public void run() {
while (p.hp > 0) {
System.out.println("Time to punch player: " + p.hp);
p.punch();
}
System.out.println("Ended");
}
}
class MyRunnable2 implements Runnable {
private int i = 100;
@Override
public void run() {
try {
while (i > 0) {
System.out.println("Running: " + i);
i--;
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Ended");
}
}