Question

My question is related to this question here. I basically want to do two tasks at the same time :

  1. collect data from a feed and add it to the list of objects
  2. read the list of objects, add it to the db and remove what is added to the db from the list of objects

So I am changing a list of objects in these two separate task and I am not sure how to share it and making it available to change by the two tasks running at the same time. The reason why I want to do it in two different task is because data from a feed is given usually every 5 seconds which gives me not enough time to process it and add it to the db.

I hope someone can help. thank you.

---- edit

I found another question which seems to give me what I need from here. So at the moment I have a code like so:

class MainThread {
    private void MainThread() {
        while(true)
       {
         //get json data

        List<Object> obj = //json data to list of object;        

        SecondThread second = new SecondThread(obj);
        second.start();
       }

    }
}

class SecondThread extends Thread {
    List<Object> obj;

    public void SecondThread(List<Object> obj) {
    this.obj = obj;
    }
    public void run() {

    //add list to db

    }
}

What I am wondering is if the while loop in the MainThread waits for the SecondThread to finish processing/putting the data in the db before it starts another loop?

Was it helpful?

Solution

Since it seems like you found something for your first set of questions, I'll answer your last question:

What I am wondering is if the while loop in the MainThread waits for the SecondThread to finish processing/putting the data in the db before it starts another loop?

In your example MainThread is never going to wait for SecondThread to finish, it will continually execute its while loop. In your code you are creating SecondThread inside of a while loop which will create tons of threads before your app crashes. If you want to wait for a thread to complete before doing other stuff then you can do:

SecondThread second = new SecondThread(obj);
second.start();
second.join(); //will make current thread wait until this thread finishes before proceeding

Note that a thread join in your case will essentially just make your code sequential since SecondThread will block MainThread from running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top