BuK/IIm10/BuK-Übung02 G2/JavaVersion
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
<language>Java</language>
<code id="4d9413de1686d">
interface Function {
boolean run(int n);
}
</code>
<code id="4d9413de168bf">
class Crazy implements Function {
public int run(int n) {
if(Haelt.haelt(this, n)) return run(n);
return n;
}
}
</code>
<code id="4d9413de16917">
class Test1 implements Runnable {
public void run() {
System.out.println("Hallo");
}
}
class Test2 implements Runnable {
public void run() {
while(true) {}
}
}
class Haelt {
public static boolean haeltFuer(Function f, int n) {
if(f.run(n)) return true;
return false;
}
public static boolean haelt(Function f) {
return haeltFuer(f, 0);
}
public static boolean haeltTricky(Runnable f, int timeout) throws InterruptedException {
Thread ft = new Thread(f);
ft.start();
while(timeout > 0) {
if(ft.getState() == Thread.State.TERMINATED) {
return true;
}
Thread.sleep(1000);
timeout--;
}
ft.stop();
return false;
}
public static void main(String[] args) {
try {
System.out.println(haeltTricky(new Test1(), 5));
System.out.println(haeltTricky(new Test2(), 5));
} catch(Exception ex) {
}
}
}
</code>