Java thread synchronization

I am working on an Android application and cannot sync View with Hardware. Let me explain.

1) I will mute the Android microphone and mute it based on random values ​​(which are random sleeps) stored in array A, from Thread 1's execution method.

2) I draw blue pulses reflecting the mute of the microphone. This is done by the independent View class.

3) I move the red line on the graph shown in the above form by calling the countdown timer inside onTick.

I start two threads one by one this way:

Thread1.start

counter.start ();

How to synchronize both of them, I want to do three things at the same time and avoid multiple threads. Three things: Draw pulses (which are constant), make the red line move along the x axis and touch the blue pulse as soon as the phone turns off, and continue to move every second, the pulse width reflects the duration of the delay. as soon as the microphone is muted, the red line should leave a momentum and move forward.

Currently, the code is doing what I want. but synchronization does not occur. Either the microphone does its job first, or the graph moves quickly. They are not synchronized.

Is there a way to hold the stream, make it behave like a coutdowntimer, or synchronize both of them. I cannot embed the movement of the red line in stream 1 because it will have to go through the x axis every second.

+3
1

, ReentrantLock "" Condition "

"wait" , , :

private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean someFlag = false;
public void threadOneMethod() {
  lock.lock();
  try {
    someFlag = true;
    condition.signalAll();
  } finally {
    lock.unlock();
  }
}
public void threadTwoMethod() {
  lock.lock();
  try {
    while (someFlag == false) {
      condition.await();
    }

    System.out.println("Did some stuff");
    someFlag = false;
  } finally {
    lock.unlock();
  }
}

"condition.await()" threadTwoMethod threadTwoMethod , threadOneMethod "condition.singalAll()". , , , , "lock.lock()/lock.unlock()".

wait() while, , , , . .

/ , , . , , , finally.

LinkedBlockQueue "", - . , , , .

+13

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


All Articles