Skip to content

Commit da84448

Browse files
committed
task2605
1 parent 54ff115 commit da84448

File tree

1 file changed

+64
-0
lines changed
  • 3.JavaMultithreading/src/com/javarush/task/task26/task2605

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.javarush.task.task26.task2605;
2+
3+
import java.util.concurrent.Executors;
4+
import java.util.concurrent.ScheduledExecutorService;
5+
import java.util.concurrent.TimeUnit;
6+
7+
/*
8+
Трудолюбие - душа всякого дела и залог благосостояния
9+
*/
10+
11+
public class Solution {
12+
private static ScheduledExecutorService interruptScheduledExecutor;
13+
private static Thread taskThread;
14+
private static RethrowableTask task;
15+
16+
public static void main(String[] args) throws Exception {
17+
runTaskBySchedule(() -> {
18+
System.out.println("A");
19+
throw new RuntimeException("it's test");
20+
}, 1_000, TimeUnit.MILLISECONDS
21+
);
22+
23+
interruptScheduledExecutor.shutdown();
24+
}
25+
26+
public static void runTaskBySchedule(final Runnable runnable, long timeout, TimeUnit unit) throws Exception {
27+
task = new RethrowableTask(runnable);
28+
taskThread = new Thread(task);
29+
taskThread.start();
30+
31+
interruptScheduledExecutor = Executors.newScheduledThreadPool(1);
32+
interruptScheduledExecutor.schedule(() -> taskThread.interrupt(), timeout, unit);
33+
Thread.sleep(unit.toMillis(timeout));
34+
try {
35+
task.rethrow();
36+
} catch (Throwable throwable) {
37+
System.out.println(throwable.getMessage());
38+
}
39+
}
40+
41+
public static class RethrowableTask implements Runnable {
42+
private volatile Throwable throwable;
43+
private Runnable runnable;
44+
45+
public RethrowableTask(Runnable runnable) {
46+
this.runnable = runnable;
47+
}
48+
49+
public void run() {
50+
try {
51+
runnable.run();
52+
} catch (Throwable throwable) {
53+
this.throwable = throwable;
54+
}
55+
}
56+
57+
public void rethrow() throws Exception {
58+
if (throwable != null) {
59+
System.out.println("B");
60+
throw new Exception(throwable);
61+
}
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)