multithreading - Passing information between EDT and other threads Java with a Handler -


i have gui (on edt thread) , thread called "recorder" created gui's eventlistener if button pressed:

if(actionevent.getsource().equals(ui.record)) {     if(recorderthread == null) {         recorder = new recorder();         recorderthread = new thread(recorder);         recorderthread.start();     } } 

in same event listener, implemented mouselistener.

public void mousereleased(mouseevent mevent) {     int x, y;      x = mevent.getxonscreen();     y = mevent.getyonscreen(); } 

i want pass these x , y variables recorder object in recorder thread when mouse clicked. think can bodge solution volatile variables, read somewhere handlers can used pass information or invoke methods between 2 threads, , interested in learning it. found this previous post faced similar problem mine.

the solution post, however, quite confused me. think person passes thread objects handler, way thread can call objects inside handler? example:

handler(someobj); 

then in thread

handler.getsomeobj().methodinobj(); 

but i'm not entirely sure if how handlers work. in addition, seem dealing swing's background thread instead of separate thread user creates(if same concept, apologies in advance).

finally, solution seems have called handler class built java library, whereas want write own handler class can better learn how threads communicate (since i'm novice youtube taught programmer). if can me out, it'd appreciated. in advance!

differntiate between concept of thread on 1 hand , concept of classes (incl. instances members) on other hand.

there various ways threads can communicate (means read or write variables @ place can written or read other threads. in example have recorder class expose public method addcoordinates(). recorder has private list member added coordinates stored. real problem synchronized access list: have ensure not 1 thread reads list whereas other thread adds new record - @ same time. easiest solution have synchronized list:

private list<coordinates> mycoordinates = collections.synchronizedlist( new arraylist<>());  public void addcoordinates( coordinates coordinates) {      // runs in context of gui thread     mycoordinates.add(coordinates);     synchronized(this)     {         this.notify();    // wakes recorder thread     }  }  public void run() {     // runs in context of recorder thread     while ( true)     {         synchronized(this)         {             this.wait();   // waits until 'this' notified         }          for( coordinates c : mycoordinates)         {             //         }     } } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -