JoinAndSleepTask.java
package ch.hslu.exercises.sw05.input.ex3;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* Parametrierbarer Task, der auf einen fremden Thread wartet und danach für
* eine bestimmte Zeit schläft.
*/
public class JoinAndSleepTask implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(JoinAndSleepTask.class);
private final String taskName;
private Thread joinFor;
private final int sleepTime;
/**
* Erzeugt einen Task mit Namen.
*
* @param taskName der Name des Tasks.
* @param sleepTime die Zeit in mSec die der Task schläft.
*/
public JoinAndSleepTask(final String taskName, final int sleepTime, Thread joinFor) {
this.taskName = taskName;
this.joinFor = joinFor;
this.sleepTime = sleepTime;
}
/**
* Hier wird auf das Ende des fremden Threads gewartet und danach für eine
* bestimmte Zeit geschlafen. Beide Teile können unterbrochen werden.
*/
@Override
public void run() {
if (null != this.joinFor) {
LOG.info("Joining Thread [{}]", this.joinFor.getName());
try {
joinFor.join();
LOG.info("Thread [{}] finished.", this.joinFor.getName());
} catch (InterruptedException e) {
LOG.warn("Thread was interrupted during join.");
Thread.currentThread().interrupt();
return;
}
} else {
LOG.info("Skipping Thread join.");
}
LOG.info("Starting sleep of {} ms", this.sleepTime);
try {
Thread.sleep(this.sleepTime);
} catch (InterruptedException e) {
LOG.warn("Thread [{}] was interrupted during sleep:", Thread.currentThread().getName());
LOG.warn(e.getMessage());
Thread.currentThread().interrupt();
return;
}
LOG.info("Task [{}] finished", this.taskName);
}
}