Results 1 to 5 of 5
  1. #1
    raghu_lzybns is offline Member
    Join Date
    Jul 2009
    Posts
    7
    Rep Power
    0

    Default Help to stop a thread

    Hi every1,
    I'm new to java and was trying to write a code which moves the character ">" from left to right in a frame when 'Start' button is pressed and stops when 'Stop' button is pressed..

    I was able to move the character when started but ..unable to stop the thread..

    Plz help..:confused:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    class AnimCar extends JFrame implements ActionListener{
        JButton bstart;
        JButton bstop;
        JButton bexit;
        int x=0;
        Font f=null;
        String t;
    
        public AnimCar(){
            bstart=new JButton("START");
            bstop=new JButton("STOP");
            bexit=new JButton("EXIT");
            Panel p1=new Panel();
            p1.add(bstart);
            p1.add(bstop);
            p1.add(bexit);
            add("South",p1);
            bstart.addActionListener(this);
            bstop.addActionListener( this);
            bexit.addActionListener(this);
            f=new Font("Arial",Font.BOLD,48);
        }
    
        @Override
        public void paint(Graphics g){
            g.setFont(f);
            g.clearRect(0, 0, 1000, 100);
            x+=10;
            if(x<=1000)
                g.drawString(">", x, 50);
            else
                x=0;
        }
    
        public static void main(String [] args){
            AnimCar ac=new AnimCar();
            ac.setVisible(true);
            ac.setSize(1000,100);
            ac.setTitle("Animation");
        }
    
       class AnimThread implements Runnable{
           volatile Thread thread;
           @Override
           public void run(){
               try{
    	           while(thread==Thread.currentThread()){
    			repaint();
                            Thread.sleep(100);
                       }
               }catch(Exception ex){
                       ex.printStackTrace();
               }
           }
    
           public void start(){
               thread=new Thread(this);
               thread.start();
           }
    
           public void stop(){
               thread=null;
           }
       }
    
       public void actionPerformed(ActionEvent ae){
    	   AnimThread at=new AnimThread();
    	   try{
    		   if(bstart==ae.getSource()){
    			   at.start();
                       }else if(ae.getSource()==bstop){
                               at.stop();
                       }else if(ae.getSource()==bexit){
                               System.exit(0);
                       }
                }catch(Exception ex){
                       ex.printStackTrace();
                }
       }
    }

  2. #2
    stevemilw is offline Member
    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Default

    concurrr mmy little ones

  3. #3
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    812
    Rep Power
    6

    Default

    Hi,
    U can't stop like this..It will not work..
    Do logically.

    1.I kept a boolean "flag";

    2.Whenever start button is pressed I have set the flag true

    3.Whenever stop button is pressed I have set the flag false

    4.In run iam running the while condition till the flag is true.

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    class AnimCar extends JFrame implements ActionListener{
        JButton bstart;
        JButton bstop;
        JButton bexit;
        int x=0;
        Font f=null;
        String t;
    	boolean flag = true;
    
        public AnimCar(){
            bstart=new JButton("START");
            bstop=new JButton("STOP");
            bexit=new JButton("EXIT");
            Panel p1=new Panel();
            p1.add(bstart);
            p1.add(bstop);
            p1.add(bexit);
            add("South",p1);
            bstart.addActionListener(this);
            bstop.addActionListener( this);
            bexit.addActionListener(this);
            f=new Font("Arial",Font.BOLD,48);
        }
    
    
        public void paint(Graphics g){
            g.setFont(f);
            g.clearRect(0, 0, 1000, 100);
            x+=10;
            if(x<=1000)
                g.drawString(">", x, 50);
            else
                x=0;
        }
    
        public static void main(String [] args){
            AnimCar ac=new AnimCar();
            ac.setVisible(true);
            ac.setSize(1000,100);
            ac.setTitle("Animation");
        }
    
       class AnimThread implements Runnable{
           volatile Thread thread;
    
           public void run(){
               try{
    	           while(flag == true){
    			repaint();
                            Thread.sleep(100);
                       }
               }catch(Exception ex){
                       ex.printStackTrace();
               }
           }
    
           public void start(){
               thread=new Thread(this);
               thread.start();
           }
    
           public void stop(){
               thread.interrupt();
           }
       }
    
       public void actionPerformed(ActionEvent ae){
    	   AnimThread at=new AnimThread();
    	   try{
    		   if(bstart==ae.getSource()){
    			   at.start();
                       }else if(ae.getSource()==bstop){
    					       flag = false;
                             
                       }else if(ae.getSource()==bexit){
                               System.exit(0);
                       }
                }catch(Exception ex){
                       ex.printStackTrace();
                }
       }
    }
    Ramya:cool:

  4. #4
    raghu_lzybns is offline Member
    Join Date
    Jul 2009
    Posts
    7
    Rep Power
    0

    Default

    ThanQ Ramya..:)
    boolean flag worked well...but can u explain the flaw in my logic

  5. #5
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    @Ramya: your way will terminate the thread, not wait like he wants.


    This one has pseudocode interspersed in it, but should work. I did extend thread, but the difference should not matter that much.

    Java Code:
    public class AnimThread extends Thread{
         private boolean terminate=false, waitFlag=false, inSleepOrWait=false;
         private Object wait=new Object;
         public AnimThread(){
              super("Animation Thread);//Always name threads!!! 
    //Thread names appear in runtime exceptions, and can be useful in tracking down the bug
    //This is especially important if you are going to use a debugger
         }
    
         public void run(){
              //I'm leaving out your actual animation
              while(!terminate){
                   //do animation
                   try{
                        inSleepOrWait=true;
                        sleep(100);
                   } catch (InterruptedException ie){
                        return;
                   }
                   if(waitFlag){
                        try{
                             wait.wait();
                        } catch(InterruptedException ie){
                             return;
                        }
                   }
                   inSleepOrWait=false;
              }
         }
         public void terminate(){
              if(inSleepOrWait)
                   interrupt();
              else terminate=true;
         }
         public void halt(){
              waitFlag=true;
         }
         public void continue(){
              waitFlag=false;
              wait.notifyAll();
         }
    }
    Also, instead of just calling system.exit(0) when the exit button is pressed, try this... It ensures that your thread gets terminated "normally" rather than abruptly closing, or worse, getting stuck.

    Java Code:
    final AnimThread at = new AnimThread();
    .....
    if(e.getSource()==bexit)
         at.terminate();
         System.exit(0);
    }
    EDIT: Missed OPs last post, though I still think this could be a better way of doing it.

    The flaw in the logic was that a thread can ignore the interrupt() method. To ensure that the thread is terminated, you need to use some form of flag.
    Last edited by Singing Boyo; 07-09-2009 at 04:42 PM.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

Similar Threads

  1. Forcing a thread to stop
    By sukatoa in forum Threads and Synchronization
    Replies: 7
    Last Post: 07-17-2009, 06:41 AM
  2. [SOLVED] How to stop a thread
    By AlejandroPe in forum New To Java
    Replies: 5
    Last Post: 04-29-2009, 03:05 PM
  3. How to stop thread from being jumping off the code without executing it.....
    By chiragkini in forum Threads and Synchronization
    Replies: 6
    Last Post: 01-22-2009, 03:38 AM
  4. how to stop a thread
    By willemjav in forum Advanced Java
    Replies: 19
    Last Post: 09-10-2008, 07:11 AM
  5. The safe way to stop a thread
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-09-2008, 06:31 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •