Start New Discussion within our Software Development Community

Its a simple program giving the demo of intre thread communication based on MovingBalls.java program...
Hopng that its Useful For U?

//Inter Thread Comminication
import java.awt.*;
import java.awt.event.*;
public class MovingBalls extends Frame implements Runnable {
	int finalPosition;
	int x1,x2,x3;
	Thread t1,t2,t3;
	public MovingBalls(){
		setLayout(new FlowLayout());
		x1 = x2 = x3 = 40;
		finalPosition = 500;
		t1 = new Thread(this);
		t2 = new Thread(this);
		t3 = new Thread(this);
		t1.start();
		t2.start();
		t3.start();
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent we){
				System.exit(0);
			}
		});
	}
	public void run(){
		try{
			while(true){
				synchronized(this){
					if(Thread.currentThread() == t1){
						if(x1 >= finalPosition){
							x1 = finalPosition;
							wait();
						}
						else{
							Thread.sleep(100);
							x1 += 20;
						}
						repaint();
					}
					if(Thread.currentThread() == t2){
						if(x2 >= finalPosition){
							x2 = finalPosition;
							wait();
						}
						else{
							Thread.sleep(100);
							x2 += 15;
						}
						repaint();
					}
					if(Thread.currentThread() == t3){
						if(x3 >= finalPosition){
							x1 = x2 = x3 = 40;
							notifyAll();
						}
						else{
							Thread.sleep(100);
							x3 += 10;
						}
						repaint();
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void paint(Graphics g){
		g.setColor(Color.red);
		g.fillOval(x1,50,50,50);
		g.fillOval(x2,150,50,50);
		g.fillOval(x3,250,50,50);
	}
	public static void main(String[] args){
		MovingBalls mb = new  MovingBalls();
		mb.setSize(600,350);
		mb.setVisible(true);
		mb.setResizable(false);
	}
}