Jeremy Comelli
Jeremy Comelli

Reputation: 15

Java, pause thread execution while condition is not met

So I have and input thread, and a processing thread. The input thread takes files, parses them and put them in a JSON queue.

public class inputThread extends Thread {
 public void run() {
  for(File f: inputFiles){
    parse();
    App.processingQueue.add(f);
  }
}

Then the processing thread polls them, and processes them.

public class processingThread extends Thread {
  //Main loop
  while(!terminated){
    App.processingQueue.poll();
    process(...);  
  }
}

Is there a simple way to pause the input thread execution when queue.size() is greater than x? I looked up synchronized blocks and wait/sleep instructions, but I couldn't get any of them to work.

Thanks!

Upvotes: 0

Views: 181

Answers (1)

Jose Zevallos
Jose Zevallos

Reputation: 725

yes, use a BlockingQueue. see here: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html

then you have to use the blocking methods: put() and take()

for example:

int MAXIMUM_CAPACITY = 10;
BlockingQueue<File> blockingQueue = new ArrayBlockingQueue(MAXIMUM_CAPACITY);
blockingQueue.put(   )
blockingQueue.take()

Upvotes: 1

Related Questions