Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java: How to stop a running thread

Java: How to stop a running thread
{filelink=10867}

import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
/****
 * Le programme Stoppe un thread
 * en cours d'exécution
 ***/
 public class StopThread extends JFrame implements Runnable
  	{
      private static final String[] listObjet =
          { "|", "/", "-", "", "|", "/", "-", "" };
       private volatile boolean stopRequested;
       private Thread monThread;
       private JTextField mascotte;
       public StopThread()
       	{
      mascotte = new JTextField();
      mascotte.setEditable(false);
      mascotte.setFont(new Font("Monospaced", Font.BOLD, 26));
      mascotte.setHorizontalAlignment(JTextField.CENTER);
      final JButton stop_anim = new JButton("Stop animation");
      stop_anim.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  stopper();
              }
          });
      JPanel pnl = new JPanel("Java Thread Example");
      pnl.setLayout(new GridLayout(0, 1, 2, 2));
      pnl.add(mascotte);
      pnl.add(stop_anim);
      setLayout(new FlowLayout(FlowLayout.CENTER));
      add(pnl);
      setTitle("Exemple de Thread");
      setSize(320, 200);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
  }
         //  Stop thread
       private void stopper()
  {
         stopRequested = true;  
        if ( monThread != null )
         {
             monThread.interrupt();
          } 
  }
       public void run() {
      try {
          monThread = Thread.currentThread();
          stopRequested = false;
          int count = 0;
          while ( !stopRequested  )
          	{
              mascotte.setText(
                  listObjet[ count % listObjet.length ]);
              Thread.sleep(200);
              count++;
          }
      } catch ( InterruptedException x )
      {
           Thread.currentThread().interrupt();
      } finally {
          monThread = null;
      }
  }
       public static void main(String[] args)
       	{
      StopThread obj = new StopThread();
      Thread thr = new Thread(obj);
      thr.start();
  		}
   }

Users who found this page were searching for:

  • how to stop a runnig thread in java
  • java stop thread
  • how to stop a class running in java

No comments yet.

Leave a Comment