1 19 20 package com.sslexplorer.activedirectory; 21 22 25 public final class ThreadRunner implements Runnable { 26 private final Thread runner; 27 private final Runnable runnable; 28 private final int sleepPeriod; 29 private boolean running; 30 31 37 public ThreadRunner(String name, Runnable runnable, int sleepPeriod) { 38 this.runner = new Thread (this, name); 39 this.runner.setPriority(Thread.NORM_PRIORITY); 40 this.runnable = runnable; 41 this.sleepPeriod = sleepPeriod; 42 } 43 44 private synchronized boolean isRunning() { 45 return running; 46 } 47 48 private synchronized void setRunning(boolean running) { 49 this.running = running; 50 } 51 52 57 public void start() { 58 if(isRunning()) { 59 throw new IllegalStateException ("ThreadRunner is already running."); 60 } 61 setRunning(true); 62 runner.start(); 63 } 64 65 69 public void stop() { 70 setRunning(false); 71 runner.interrupt(); 72 } 73 74 public void run() { 75 while (isRunning()) { 76 runnable.run(); 77 sleep(); 78 } 79 } 80 81 private void sleep() { 82 try { 83 Thread.sleep(sleepPeriod); 84 } catch (InterruptedException e) { 85 } 87 } 88 } | Popular Tags |