Inter Thread Communication!

yash301288 yash301288 is offline Offline Aug 10th, 2008, 12:15 pm |
0
Its a simple program giving the demo of intre thread communication based on MovingBalls.java program...
Hopng that its Useful For U?
Quick reply to this message  
Java Syntax
  1. //Inter Thread Comminication
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. public class MovingBalls extends Frame implements Runnable {
  5. int finalPosition;
  6. int x1,x2,x3;
  7. Thread t1,t2,t3;
  8. public MovingBalls(){
  9. setLayout(new FlowLayout());
  10. x1 = x2 = x3 = 40;
  11. finalPosition = 500;
  12. t1 = new Thread(this);
  13. t2 = new Thread(this);
  14. t3 = new Thread(this);
  15. t1.start();
  16. t2.start();
  17. t3.start();
  18. addWindowListener(new WindowAdapter(){
  19. public void windowClosing(WindowEvent we){
  20. System.exit(0);
  21. }
  22. });
  23. }
  24. public void run(){
  25. try{
  26. while(true){
  27. synchronized(this){
  28. if(Thread.currentThread() == t1){
  29. if(x1 >= finalPosition){
  30. x1 = finalPosition;
  31. wait();
  32. }
  33. else{
  34. Thread.sleep(100);
  35. x1 += 20;
  36. }
  37. repaint();
  38. }
  39. if(Thread.currentThread() == t2){
  40. if(x2 >= finalPosition){
  41. x2 = finalPosition;
  42. wait();
  43. }
  44. else{
  45. Thread.sleep(100);
  46. x2 += 15;
  47. }
  48. repaint();
  49. }
  50. if(Thread.currentThread() == t3){
  51. if(x3 >= finalPosition){
  52. x1 = x2 = x3 = 40;
  53. notifyAll();
  54. }
  55. else{
  56. Thread.sleep(100);
  57. x3 += 10;
  58. }
  59. repaint();
  60. }
  61. }
  62. }
  63. }catch(Exception e){
  64. e.printStackTrace();
  65. }
  66. }
  67. public void paint(Graphics g){
  68. g.setColor(Color.red);
  69. g.fillOval(x1,50,50,50);
  70. g.fillOval(x2,150,50,50);
  71. g.fillOval(x3,250,50,50);
  72. }
  73. public static void main(String[] args){
  74. MovingBalls mb = new MovingBalls();
  75. mb.setSize(600,350);
  76. mb.setVisible(true);
  77. mb.setResizable(false);
  78. }
  79. }

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC