Search code examples
javaandroidrunnablethread-sleepinterrupted-exception

How to interrupt a thread by button listener


I have a button listener witch include a thread sleep and another button listener.

Second button listener must interrupt this thread and I don t know how to do this:

My code:

button1.setOnClickListener (new View.OnClickListener() {

        @Override
        public void onClick(View v) {


..........


                button1.setEnabled(false);
                button1.setVisibility(View.GONE);
                button2.setVisibility(View.VISIBLE);
                button2.setEnabled(true);


                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2800);
                        } catch (InterruptedException e) {
                          // ???????
                        }

                        MainActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                button1.setEnabled(true);
                                button1.setVisibility(View.VISIBLE);
                                button2.setEnabled(false);
                                button2.setVisibility(View.GONE);
                            }
                        });
                    }
                }).start();



 button2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


..............


         //  Thread.interrupted(); -> does not work


                    }
                });

}   });

How can I make button2 listener to interrupt the thread?


Solution

  • Instead of an anonymous implementation of the thread, make the thread a class variable. Suppose the name of the thread is btnOneThread

    private Thread btnOneThread;
    

    Initialize the thread where needed and start it.

    btnOneThread = new Thread( ){...}
    btnOneThread.start();
    

    When the button2 is clicked call

    if (btnOneThread != null) {
        btnOneThread.interrupt();
    }