0

I am trying to use thread wait and notify function, but noticed that notify function not calling my method again. Sharing my code. Please let me know what I'm doing wrong.

public class MainActivity extends AppCompatActivity {
    Thread t;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         t = new Thread(new Runnable() {
            @Override
            public void run() {
                List<Parent> threadList = new ArrayList<>();
                threadList.add(new Task1(MainActivity.this));
                threadList.add(new Task2(MainActivity.this));
                for (Parent task : threadList) {
                    try {
                        task.execute();
                        t.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
         t.start();
    }

    public void getResult(int i) {
        Log.i("@@@","Notified"+i);
        t.notify();
    }
}
class Task1 implements Parent{
    public int total;
    MainActivity mainActivity;
    Task1 (MainActivity c) {
        mainActivity = c;
    }
    @Override
    public void execute() {
        for(int i=0; i<200 ; i++){
            total += i;
            Log.i("@@@1", ""+i);
        }
        mainActivity.getResult(1);
    }
}

Task 2 is not getting executed after Task1

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • There is so much wrong with your code, I'm not sure where to start... You should **never** call `wait()` on a `Thread` instance, you can also only ever call `wait` or `notify` if you have synchronized on the object in question (again, which you should **never** do on a `Thread`). Your task currently probably fails with an exception anyway because of that. Also given you execute task1 and task2 sequentially on a single thread, you should never wait **at all**, because the subsequent task will never execute. – Mark Rotteveel Feb 01 '19 at 13:40
  • Related: https://stackoverflow.com/questions/16197135/how-can-the-wait-and-notify-methods-be-called-on-objects-that-are-not-thread – Mark Rotteveel Feb 01 '19 at 13:46
  • you are not creating different threads. So `task.execute();` is called which calls `mainActivity.getResult(1);` which calls `t.notify();`. This all happens before actual call to `t.wait();` so thread is notified before any wait is added. so now, its waiting for another notify which never happens. – Rahul Feb 01 '19 at 14:27

0 Answers0