1 package nl.tudelft.simulation.language.concurrent;
2
3 import java.util.concurrent.atomic.AtomicBoolean;
4
5 import org.djutils.logger.CategoryLogger;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 public class WorkerThread extends Thread
22 {
23
24 private Runnable job = null;
25
26
27 private boolean finalized = false;
28
29
30 private AtomicBoolean running = new AtomicBoolean(false);
31
32
33
34
35
36
37 public WorkerThread(final String name, final Runnable job)
38 {
39 super(name);
40 this.job = job;
41 this.setDaemon(false);
42 this.setPriority(Thread.NORM_PRIORITY);
43 this.start();
44 }
45
46
47
48
49 public synchronized void cleanUp()
50 {
51 this.running.set(false);
52 this.finalized = true;
53 if (!this.isInterrupted())
54 {
55 this.notify();
56 }
57 this.job = null;
58 }
59
60
61
62
63 public synchronized boolean isRunning()
64 {
65 return this.running.get();
66 }
67
68
69 @Override
70 public synchronized void run()
71 {
72 while (!this.finalized)
73 {
74 try
75 {
76 this.wait();
77 }
78 catch (InterruptedException interruptedException)
79 {
80 if (!this.finalized)
81 {
82 this.interrupt();
83 try
84 {
85 this.running.set(true);
86 this.job.run();
87 this.running.set(false);
88 }
89 catch (Exception exception)
90 {
91 CategoryLogger.always().error(exception);
92 }
93 Thread.interrupted();
94 }
95 }
96 }
97 }
98 }