package t1;
import java.util.Timer;
import java.util.TimerTask;
public class TestThread27 {
static enum Direction {
/** 前進 */
FORWARD("前進", 1),
/** 后退 */
BACKWARDS("后退", 2);
private final String action;
private final int code;
Direction(String action, int code) {
this.action = action;
this.code = code;
}
public String getAction() {
return action;
}
public int getCode() {
return code;
}
}
public static void main(String[] args) {
TimerTask task = new TimerTask() {
final static int MAXSTEPS = 4;
volatile int direction = Direction.FORWARD.getCode();
volatile int steps = 0;
@Override
public void run() {
switch (direction) {
case 1:
System.out.print(' ');
System.out.print("*");
steps++;
break;
case 2:
System.out.print(' ');
System.out.print("#");
steps++;
break;
}
if (steps == MAXSTEPS) {
direction = (direction == Direction.FORWARD.getCode())
? Direction.BACKWARDS.getCode()
: Direction.FORWARD.getCode();
steps = 0;
}
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 500);
}
}
輸出結果:
............