1  /*
  2   * Bouncing balls - each ball is a different thread with a different
  3   * time to sleep.
  4   */
  5  
  6  import java.awt.*;
  7  import java.awt.event.*;
  8  
  9  public class BounceSynch extends Frame implements ActionListener
 10  {
 11     private Canvas canvas;
 12  
 13     public BounceSynch()
 14     {  setLayout(new BorderLayout());
 15        setTitle("BounceSynch");
 16  
 17        canvas = new Canvas();
 18        add(canvas, BorderLayout.CENTER);
 19  
 20        Panel p = new Panel();
 21        Button b1 = new Button("Start");
 22        b1.addActionListener(this);
 23        p.add(b1);
 24        Button b2 = new Button("Close");
 25        b2.addActionListener(this);
 26        p.add(b2);
 27        add(p, BorderLayout.SOUTH);
 28     }
 29     
 30     public void actionPerformed(ActionEvent evt)
 31     {  if (evt.getActionCommand().equals("Start"))
 32        {  BallSynch b = new BallSynch(canvas);
 33           b.start();
 34        }
 35        else if (evt.getActionCommand().equals("Close"))
 36           System.exit(0);
 37     }
 38   
 39     public static void main(String[] args)
 40     {  Frame f = new BounceSynch();
 41        f.setSize(400, 300);
 42        f.setVisible(true);  
 43     }
 44     
 45  }
 46  
 47  class BallSynch extends Thread
 48  {  
 49     private Canvas box;
 50     private static final int XSIZE = 10;
 51     private static final int YSIZE = 10;
 52     private int x = 0;
 53     private int y = 0;
 54     private int dx = 2;
 55     private int dy = 2;   
 56     private int sleeptime;
 57  
 58     public BallSynch(Canvas c) 
 59     { box = c;
 60       sleeptime = ((int)(Math.random() * 40)) + 4;
 61     }
 62  
 63     public synchronized void draw()
 64     {  Graphics g = box.getGraphics();
 65        g.fillOval(x, y, XSIZE, YSIZE);
 66        g.dispose();
 67     }
 68     
 69     public synchronized void move()
 70     {  Graphics g = box.getGraphics();
 71        g.setXORMode(box.getBackground());
 72        g.fillOval(x, y, XSIZE, YSIZE);
 73        x += dx;
 74        y += dy;
 75        Dimension d = box.getSize();
 76        if (x < 0) { x = 0; dx = -dx; }
 77        if (x + XSIZE >= d.width) { x = d.width - XSIZE; dx = -dx; }
 78        if (y < 0) { y = 0; dy = -dy; }
 79        if (y + YSIZE >= d.height) { y = d.height - YSIZE; dy = -dy; }
 80        g.fillOval(x, y, XSIZE, YSIZE);
 81        g.dispose();
 82     }
 83     
 84     public void run()
 85     {  draw();
 86        for (int i = 1; i <= 1000; i++)
 87        {  move();
 88           try { Thread.sleep(sleeptime); } catch(InterruptedException e) {}
 89        }
 90     }
 91  }
 92  
 93  
 94