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);
    }
}
输出结果:

............
原文:https://www.cnblogs.com/dengw125792/p/12613647.html