2014-07-23 21:03:03 +10:00
package codechicken.nei ;
2022-06-24 12:32:13 +01:00
public abstract class RestartableTask {
2014-07-23 21:03:03 +10:00
public final String name ;
private Thread thread ;
private volatile boolean restart ;
private volatile boolean stopped ;
private ThreadOperationTimer timer ;
public RestartableTask ( String name ) {
this . name = name ;
}
private void start () {
thread = new Thread ( name ) {
@Override
public void run () {
do {
2022-06-24 12:32:13 +01:00
while ( stopped )
try {
Thread . sleep ( 1 );
} catch ( InterruptedException ignored ) {
}
if ( ! restart ) execute ();
} while ( ! finish ());
2014-07-23 21:03:03 +10:00
}
};
thread . start ();
}
private synchronized boolean finish () {
2022-06-24 12:32:13 +01:00
if ( restart ) {
2014-07-23 21:03:03 +10:00
restart = false ;
return false ;
} else {
clearTasks ();
return true ;
}
}
public void clearTasks () {
thread = null ;
timer = null ;
}
public synchronized void restart () {
2022-06-24 12:32:13 +01:00
if ( thread != null ) {
2014-07-23 21:03:03 +10:00
stopped = false ;
restart = true ;
2022-06-24 12:32:13 +01:00
} else start ();
2014-07-23 21:03:03 +10:00
}
/**
* Stops execution until restart is called. If a thread is running, the restart flag will be set, and the thread will be paused once the execute method exits.
*/
public synchronized void stop () {
2022-06-24 12:32:13 +01:00
if ( thread != null ) {
2014-07-23 21:03:03 +10:00
stopped = true ;
restart = true ;
}
}
public boolean interrupted () {
return restart ;
}
public synchronized ThreadOperationTimer getTimer ( int timeout ) {
if ( timer == null ) timer = ThreadOperationTimer . start ( thread , timeout );
return timer ;
}
public abstract void execute ();
}