multithreading - Java synchronizing Threads with Swing -


i've written program displays balls in window moving , absorb each other probability when getting in contact.

the current version works, balls's movement been calculated every time paintcomponent method (implicitely) invoked:

public class colliderpanel extends jpanel { ...  @override public void paintcomponent(graphics g){     super.paintcomponent(g);      // calculate balls's movement     random r = new random();         listiterator<ball> = cp.getcolliderpanel().balls.listiterator();         vector<ball> ballstoremove = new vector<ball>();          while (it.hasnext()) {             ball b = it.next();             b.move(1.0 / 60.0);             b.collideframe(cp.getcolliderpanel().getsize());              listiterator<ball> it2 = cp.getcolliderpanel().balls.listiterator(it.nextindex());             while (it2.hasnext()) {                 ball b2 = it2.next();                 if (b.collide(b2)) {                     if (r.nextdouble() < 0.5) {                         if (b.m > b2.m) {                             b.swallow(b2);                             ballstoremove.add(b2);                         } else {                             b2.swallow(b);                             ballstoremove.add(b);                         }                     }                 }             }         }          cp.getcolliderpanel().balls.removeall(ballstoremove);          try {             thread.sleep((long) (1000.0 / 60.0));         } catch (interruptedexception e) {             e.printstacktrace();         }      for(ball b : balls) b.draw(g);      repaint(); }  ... } 

now want outsource calculation of balls's movement second thread. tried create class simulateballsmovement implements runnable calculation in overriden run method , created new thread in colliderpanel, has simulateballsmovement runnable-object.

public class colliderpanel extends jpanel { private thread simthread = new thread(new simulateballsmovement());  @override public void paintcomponent(graphics g){     super.paintcomponent(g);      // calculate balls's movement     // to here? how synchronize painting , calculation?      for(ball b : balls) b.draw(g);      repaint(); }  ... } 

my problem don't know how synchronize painting of balls , movement calculation? colliderpanel need thread member? found tutorials on how synchronize 2 threads invoke same method, want here?

this looks classic producer consumer scenario. thread calculates ball movements producer , thread paints them consumer. check out these tutorial on topic: http://www.tutorialspoint.com/javaexamples/thread_procon.htm or https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html


Comments