From 3f505e751becce50e03c4af87cee6776375a5013 Mon Sep 17 00:00:00 2001 From: 2wenty1ne Date: Mon, 14 Oct 2024 20:24:46 +0200 Subject: [PATCH] Assigment finished --- src/src/Runner.java | 24 ++++++++++++++++++++++++ src/src/Task.java | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/src/Runner.java create mode 100644 src/src/Task.java diff --git a/src/src/Runner.java b/src/src/Runner.java new file mode 100644 index 0000000..50c29b5 --- /dev/null +++ b/src/src/Runner.java @@ -0,0 +1,24 @@ + +public class Runner { + public static void main(String... args) { + var task = new Task(); + var thread = new Thread(task); + thread.setUncaughtExceptionHandler((t, e) -> { + System.err.println("Unhandled Exception: " + e.getMessage()); + System.err.println(" Thread: " + t.threadId() + " - " + t.getName()); + System.err.println(" Thread State: " + t.getState()); + e.printStackTrace(System.err); + }); + thread.start(); +// var killer = new Thread(() -> { +// try { +// Thread.sleep(300); +// } catch (InterruptedException e) { +// throw new RuntimeException(e); +// } +// task.stopRequest(); +// }); + //killer.start(); + (new Thread(() -> task.stopRequest())).start(); + } +} diff --git a/src/src/Task.java b/src/src/Task.java new file mode 100644 index 0000000..f346f63 --- /dev/null +++ b/src/src/Task.java @@ -0,0 +1,33 @@ +public class Task implements Runnable { + private volatile Thread self; + private volatile boolean stopped = false; + + public void stopRequest() { + this.stopped = true; + if (this.self != null) { + this.self.interrupt(); + } + } + + public boolean isStopped() { + return this.stopped; + } + + @Override + public void run() { + this.self = Thread.currentThread(); + // 1. Initialisierungsphase + var i = 100; + while (!isStopped()) { + // 2. Arbeitsphase + System.out.println("i=" + i); + try { + Thread.sleep(1000 / i--); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + // 3. Aufräumphase + System.out.println("fertig."); + } +} \ No newline at end of file