This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
NTW/hw2/src/transport/MyTimer.java

82 lines
2.1 KiB
Java

package transport;
import java.util.Vector;
class MyTimer implements Runnable {
Object monitor;
Vector<ScheduledAction> actions;
boolean active;
public MyTimer(Object var1) {
this.monitor = var1;
this.actions = new Vector();
this.active = true;
Thread var2 = new Thread(this);
var2.setDaemon(true);
var2.start();
}
public synchronized void stop() {
this.active = false;
}
public synchronized void schedule(TimeoutAction var1, long var2) {
long var4 = System.currentTimeMillis() + var2;
int var6;
for(var6 = 0; var6 < this.actions.size() && ((ScheduledAction)this.actions.elementAt(var6)).time < var4; ++var6) {
}
this.actions.insertElementAt(new ScheduledAction(var4, var1), var6);
this.notify();
}
synchronized TimeoutAction getFirst() throws InterruptedException {
while(true) {
if (this.active) {
if (this.actions.isEmpty()) {
this.wait();
continue;
}
long var1 = ((ScheduledAction)this.actions.elementAt(0)).time - System.currentTimeMillis();
if (var1 > 0L) {
this.wait(var1);
continue;
}
return ((ScheduledAction)this.actions.remove(0)).action;
}
return null;
}
}
public synchronized void cancel(TimeoutAction var1) {
for(int var2 = 0; var2 < this.actions.size(); ++var2) {
if (((ScheduledAction)this.actions.elementAt(var2)).action == var1) {
this.actions.remove(var2);
break;
}
}
}
public void run() {
try {
while(true) {
TimeoutAction var1 = this.getFirst();
if (var1 == null) {
return;
}
synchronized(this.monitor) {
var1.timeoutAction();
}
}
} catch (Exception var5) {
System.err.println("MyTimer: " + var5);
}
}
}