user285594
user285594

Reputation:

How to access the running thread/runnable?

I have a thread running but from outside I can't bypass a value to stop that thread. How can I send false/true value inside Mytest() or call running thread public methods? When I press the button1? ex: thread.interrupt(); runnable.stop(); or runnable.start();

// Main
public class Main extends JFrame
{
  public static Runnable runnable;
  public static Thread thread;
  private JButton b1    = new JButton("Start/Stop");

  public void init() 
  {    
    //Execute a job on the event-dispatching thread:
    try {
       javax.swing.SwingUtilities.invokeAndWait(new Runnable() 
       {
         public void run() 
         {
            createGUI();
         }
        });
     } catch (Exception e) { 
       System.err.println("createGUI didn't successfully complete");
     }
  }

  public void createGUI()
  {
    Container cp = getContentPane();
    b1.addActionListener(new button1()); cp.add(b1);
    runnable = new Mytest();
    thread = new Thread(runnable);
    thread.start();
  }
}

// Button 1 - [problem to go  inside a running thread]
public class button1 implements ActionListener 
{
  public void actionPerformed(ActionEvent e) 
  {
    System.out.println("button pressed - need to access ");
      //thread.interrupt();       runnable.stop(); //or runnable.start();
  }
}

// Running - Thread
public class Mytest implements Runnable
{
  public static boolean onoff = false;
  public static boolean status = false;

  public void run()
  {
    while(true) 
    {
      if (onoff) 
      {
         return;
       } else { 
         if (status==false) System.out.println("running"); 
       }
    }
  }
  public static void stop() { status = true; onoff=true; }
  public static void start() { status = false; onoff = false; }
}

Follow up (proof read):

Step 1:

/* Main -  boot/startup */
public class Main extends JFrame
{
    public static Mytest runnable;  // wrong: public static Runnable runnable;
    public static Thread thread;
    private JButton b1    = new JButton("Start");
    private JButton b2    = new JButton("Stop");  

  public void init() 
  {    
    // Execute a job on the event-dispatching thread:
    // In case Freezed for heavy lifting
    try {
       javax.swing.SwingUtilities.invokeAndWait(new Runnable() 
       {
         public void run() 
         {
            createGUI();
         }
       });
     } catch (Exception e) { 
       System.err.println("createGUI didn't successfully complete");
     }
  }

  public void createGUI()
  {
    Container cp = getContentPane();
    b1.addActionListener(new button1()); 
    cp.add(b1);

    runnable = new Mytest();
    thread = new Thread(runnable);    
        try {
                thread.sleep(100);  // value is milliseconds        
                thread.start();     
        } catch (InterruptedException e) {              
        }
  }

  public static void main(String[] args)
  {        
    run(new Main(), 500, 500);
  }

  public static void run(JFrame frame, int width, int height) 
  {        ...
    frame.setVisible(true);
  }
}

/* To start */
public class button1 implements ActionListener 
{
  public void actionPerformed(ActionEvent e) 
  {
    runnable.start();
  }    
}

/* To stop */
public class button2 implements ActionListener 
{
  public void actionPerformed(ActionEvent e) 
  {
    runnable.stop();
  }    
}

Step 2:

/* Thread deals */
public class Mytest implements Runnable
{
  private static volatile boolean running = true;

  public void run()
  {
    while(running) 
    {
      // do stuff
    }
  }
  public void start() { running = true; }
  public void stop()  { running = false;}
}

Upvotes: 9

Views: 36704

Answers (5)

David O'Meara
David O'Meara

Reputation: 3033

if you define it by class rather than as a Runnable you can call the instance methods.

public static Mytest runnable;

Also note that due to multiple cores having their own associated memory, you need to warn the processor that the state may be changed on another processor and that it needs to watch for that change. Sounds complicated, but just add the 'volatile' keyword to the boolean flags

public class Mytest implements Runnable
{
  private static volatile boolean running = true;

  public void run()
  {
    while(running) {
      // do stuff
    }
  }

  public void stop() { running = false;}
}

Start the Runnable as in your initial code, then shut it down using runnable.stop()

Upvotes: 7

Robert Höglund
Robert Höglund

Reputation: 979

You should always use the interrupt method to stop a thread. This is a safe and the adequate way to perform a stop operation an a thread.

Thread tThread = new Thread(new Runnable() {

                public void run() {
                        while (!Thread.currentThread().isInterrupted()) {
                        try{
                        Thread.sleep(10);
                        ... do you stuff...
                        }catch(InterruptedException ex){

                            break;
                        }
                    }

                }

            });
    tThread.start();

And when you would like to stop you thread just invoke the interrupt method:

tThread.interrupt();

Upvotes: 6

RollingBoy
RollingBoy

Reputation: 2817


public void run()
  {
    while(!isInterrupted()) {
      if (onoff) {
         return;
       } else { 
         if (status==false) System.out.println("running"); 
       }
    }
  }


Then use Thread.interrupt() to indicate a interrption of the thread.

Note: Don't use Thread.stop() under any circumstance! It's Deprecated!
For more detail, JDK document and << Java Concurrency in Practice >> can be referred to.

Upvotes: 2

krackmoe
krackmoe

Reputation: 1763

in your run method...

dont do while(true)..

use a boolean... like... while(threadIsRunning)

and this boolean you can set to true/false....

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114787

Apart from the fact, that this thread is a heating test for your CPU ;)

You can call the start/stop methods with

 MyThread.start();
 MyThread.stop();

You've defined them as static methods, so the above lines of code show how to call them.

for the heating... add something like

try {
    Thread.sleep(100);  // value is milliseconds
} catch (InterruptedException e) {
    // no need to handle (in this example)
}

This will reduce the CPU load from 100% (on one core) to a reasonable value ;)

Upvotes: 0

Related Questions