-1

i started a thread when activity created in android

when click stop it will interrupt the thread to see my data on particular time after that i start the thread by clicking button start it will start the thread again

sometime it work properly, sometime i get Interrupted error,

strt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             Drawer.start();
   });
    stp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Drawer.interrupt();  });

what to do?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Assuming `Drawer` is a Thread, you can't start it twice: ["It is never legal to start a thread more than once"](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#start()) – Andy Turner May 14 '19 at 06:29
  • @AndyTurner I start that after i interrupt the thread..is that good to do? – Codefordina May 14 '19 at 06:31

1 Answers1

1

Assuming Drawer is a Thread, you can't start it twice: "It is never legal to start a thread more than once". Your basic assumptions about how to write this code are flawed.

I would suggest not using threads directly. Instead. Use an ExecutorService, for example:

ExecutorService executor = Executors.newFixedThreadPool(1);

Then, submit work to this pool in your start button's onClickListener:

future = executor.submit(runnable);

where runnable is the work you want to do.

The returned Future is a thing which conveys the result of running runnable, but also lets you do things like cancel it (i.e. ask it to stop running):

future.cancel(true);

where true means that you want to interrupt the underlying thread which is running it.

Hence, store future in a member variable when you press the start button, and then cancel it as above when you press the stop button.

Note that you need to make your runnable handle interruption: this is not something which happens "for free". Interruption is a cooperative mechanism: code is free to respond to interruption (or not).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243