线程的休眠

public class SleepMethodTest extends JFrame {

    private Thread t;
    private static Color[] color = { Color.BLACK, Color.BLUE, Color.CYAN, Color.GREEN, Color.ORANGE, Color.YELLOW,
            Color.RED };
    private static final Random rand = new Random();

    private static Color getC() {
        return color[rand.nextInt(color.length)];
    }

    public SleepMethodTest() {
        // TODO Auto-generated constructor stub
        t = new Thread(new Runnable() {
            int x = 30;
            int y = 50;
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                    Graphics graphics = getGraphics();
                    graphics.setColor(getC());
                    graphics.drawLine(x, y, 100, y++);
                    if(y>=80){
                        y=50;
                    }
                }

            }
        });
        t.start();
    }
    public static void init(JFrame frame,int width,int height) {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        init(new SleepMethodTest(), 100, 100);
    }

}

猜你喜欢

转载自www.cnblogs.com/dulute/p/10648040.html
今日推荐