Thread

スレッドの実装に方法には次の2つがある. クラス宣言において,


プログラム例

    import java.awt.*;
    import javax.swing.*;

    public class Ball extend JApplet implements Runnable {
        Thread thread;
        int x = 0, y = 0;
        int addx = 5, addy = 5;

        public void init() {
            thread = new Thread(this);   // スレッドを生成する
            thread.start();
        }

        public void run() {              // スレッドの処理
            for (int i = 10000 ; i > 0; i-- ) {
                x += addx;
                y += addy;
                if (x == 390)    addx = -5;
                else if( (x==0)  addx = 5;
                repaint();
                try {
                    thread.sleep(100);  // 一時停止
                }
                catch (InterruptedException e) { } // 例外処理
            }
        }

        public void paint(Graphics g) {
            super.paint(g);
            g.setColor(Color.BLUE);
            g.fillOval(x, y, 10, 10);
        }
    }