Zkouším v naší J2EE aplikaci udělat jednoduchý časovač. Spouštím jej zatím
z jsp stránky
Clock clk = Clock.getInstance();
clk.start();
Časovač existuje v jedné instanci dokud neopustím kontext jsp stránky.
Jakmile spustím novou stránku, vytvoří se další instance, což nechci. Lze
časovač napsat tak, aby se spuštěl spolu se serverem a aby šlo z jsp
stránek se dostat vždy na jeho jednu jedinou instanci ?
J.N.
public class Clock implements Runnable {
Thread timer = null;
static private Clock instance;
public static Clock getInstance() {
if (instance == null) {
instance = new Clock();
}
return instance;
}
public void start() {
if(timer == null) {
timer = new Thread(this);// "this" tells the thread
// to go to this Runnable
// object to get the Run() function.
timer.start();
}
}
public void stop() {
timer = null; // The garbage collector will see that
// now there is no reference to the Thread
// object and delete it.
}
public void run() {
while (timer != null) {
try {
Thread.sleep(1000);// sleep for 1s
} catch (InterruptedException e){}
System.out.println("Tik");
}
timer = null;
}
}