How to synchronize (d) methods and change the properties of objects in the parent object?

I have two threads running from a controller class. The first thread receives SMS messages and should continue to work while the program is in a running state. Another stream is used to calculate the location of GPS blocks.

The controller starts the SMS stream and waits for a text message. If the text message meets certain criteria, the GPS location stream starts and the coordinates are sent back to the controller.

For each stream, I used the following format:

reader = new Reader(this);
        new Thread(reader).start();

Then the reader class uses the controller reference so that it can call the method in the controller:

public void ReceivedCommand(String address) {
    [..]
}

GPS, (?), ReceivedLocation, SMS- ( TextMessage). , SMS ( ), GPS, SMS-.

, 2 , ( TextMessage), , ( ) , GPS GPSLocation.

ReceivedCommand():

  • TextMessage,
  • GPS
  • GPS (ReceivedLocation())
  • TextMessage?
+3
1

-, . , ( java.util.concurrent (a ExecutorService)

synchronized , synchronized . , synchronized, (.. ), , :

final TextMessage msg = //...
Thread t = new Thread(r);
synchronized (msg) {
    t.start();
} //the other thread is still running and now this thread has not synchronized on the msg

r:

Runnable r = new Runnable() {
    public void run() {
        synchronized (msg) { //only any use if readers are alse sync-ed
            msg.setGpsLocation(findGpsLocation(msg)); 
        }
    }
}

TextMessage (.. - synchronized), , .

, synchronized , , (, , , , , ).

ExecutorService:

final TextMessage msg = //...
ExecutorService worker = Executors.newSingleThreadedExecutor();
Future<?> f = worker.submit(r); //the future represents the work

r :

Runnable r = new Runnable() {
    public void run() {
        GpsLocation  loc = findGpsLocation(msg);
        msg.setGpsLocation(loc); //the setter is synchronized
    }
}

setGpsLocation synchronized ( getter , ). , , . , - , synchronize , :

synchronized (msg) {
    if (msg.getGpsLocation().isIn(AMERICA))
       msg.append(" DUDE!")
}
+4

Source: https://habr.com/ru/post/1714947/


All Articles