0

How create a button which pause the thread which is inside the loop and another button which resumes.

Runnable myRun = new Runnable(){

public void run(){

   for(int j =0 ;j<=words.length;j++){

       synchronized(this){
           try {

                wait(sleepTime);

                bt.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {

                                try {
                                    wait();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                    }});
                bt2.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        notify();

                    }
                });
                } catch (InterruptedException e) {
                e.printStackTrace();

            } }
       runOnUiThread(new Runnable(){
           public void run(){
               try {
                    et.setText(words[i]);
                    i++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
           }});
      }}};

doing some stuff say words.lenght=1000 times
then suppose user want to take break in between
click pause button with id = bt this button pauses thread until and user clicks resume with id= bt1

lavin
  • 1
  • 2

2 Answers2

0

Below is a hint , i think you can use for your problem. Its copied from the link i pasted at end.

A wait can be "woken up" by another process calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:

Object mon = ...;
synchronized (mon) {
    mon.wait();
}

At this point the currently executing thread waits and releases the monitor. Another thread may do

synchronized (mon) { mon.notify(); }(On the same mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.

Check Difference between wait() and sleep()

Community
  • 1
  • 1
manishpro
  • 141
  • 8
0

You do it like this:

How to indefinitely pause a thread in Java and later resume it?

Only you call the suspend() and other methods from your buttons' OnClickListeners

Community
  • 1
  • 1
Ivan Bartsov
  • 19,664
  • 7
  • 61
  • 59