View Javadoc
1   package ch.hslu.exercises.sw05.input.ex3;
2   
3   import org.slf4j.LoggerFactory;
4   import org.slf4j.Logger;
5   
6   /**
7    * Parametrierbarer Task, der auf einen fremden Thread wartet und danach für
8    * eine bestimmte Zeit schläft.
9    */
10  public class JoinAndSleepTask implements Runnable {
11  
12      private static final Logger LOG = LoggerFactory.getLogger(JoinAndSleepTask.class);
13      private final String taskName;
14      private Thread joinFor;
15      private final int sleepTime;
16  
17      /**
18       * Erzeugt einen Task mit Namen.
19       *
20       * @param taskName  der Name des Tasks.
21       * @param sleepTime die Zeit in mSec die der Task schläft.
22       */
23      public JoinAndSleepTask(final String taskName, final int sleepTime, Thread joinFor) {
24          this.taskName = taskName;
25          this.joinFor = joinFor;
26          this.sleepTime = sleepTime;
27      }
28  
29      /**
30       * Hier wird auf das Ende des fremden Threads gewartet und danach für eine
31       * bestimmte Zeit geschlafen. Beide Teile können unterbrochen werden.
32       */
33      @Override
34      public void run() {
35          if (null != this.joinFor) {
36              LOG.info("Joining Thread [{}]", this.joinFor.getName());
37              try {
38                  joinFor.join();
39                  LOG.info("Thread [{}] finished.", this.joinFor.getName());
40              } catch (InterruptedException e) {
41                  LOG.warn("Thread was interrupted during join.");
42                  Thread.currentThread().interrupt();
43                  return;
44              }
45          } else {
46              LOG.info("Skipping Thread join.");
47          }
48  
49          LOG.info("Starting sleep of {} ms", this.sleepTime);
50          try {
51              Thread.sleep(this.sleepTime);
52          } catch (InterruptedException e) {
53              LOG.warn("Thread [{}] was interrupted during sleep:", Thread.currentThread().getName());
54              LOG.warn(e.getMessage());
55              Thread.currentThread().interrupt();
56              return;
57          }
58  
59          LOG.info("Task [{}] finished", this.taskName);
60      }
61  }