Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 07-09-2009, 01:53 PM
Member
 
Join Date: Jul 2009
Posts: 7
Rep Power: 0
raghu_lzybns is on a distinguished road
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..
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();
            }
   }
}
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 07-09-2009, 02:50 PM
Member
 
Join Date: Jul 2009
Posts: 6
Rep Power: 0
stevemilw is on a distinguished road
Default
concurrr mmy little ones
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 07-09-2009, 02:58 PM
RamyaSivakanth's Avatar
Senior Member
 
Join Date: Apr 2009
Location: Chennai
Posts: 533
Rep Power: 1
RamyaSivakanth is on a distinguished road
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.

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
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 07-09-2009, 05:31 PM
Member
 
Join Date: Jul 2009
Posts: 7
Rep Power: 0
raghu_lzybns is on a distinguished road
Default
ThanQ Ramya..
boolean flag worked well...but can u explain the flaw in my logic
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 07-09-2009, 05:39 PM
Senior Member
 
Join Date: Mar 2009
Posts: 376
Rep Power: 1
Singing Boyo is on a distinguished road
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.

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.

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.
__________________
So you came along and found Java? Randomly?
Well then, you're just like me!

Last edited by Singing Boyo; 07-09-2009 at 05:42 PM.
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


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


All times are GMT +2. The time now is 03:40 PM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org