Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Stop a thread?

  1. #1
    Member
    Join Date
    Feb 2013
    Posts
    78
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Stop a thread?

    Hey guys. So, I have yet to truly know how to properly stop a thread. Thus, I have an example and I am wondering if I am stopping the thread the correct way. I would also like to know, can you call .start on a stopped thread to restart it?
    Heres the example:
    package com.sci;
     
    import com.sci.rpi.api.RaspberryPi;
     
    public class RPI implements Runnable
    {
    	private Thread thread;
    	private boolean running;
     
    	public RPI()
    	{
                    thread = new Thread(this);
    	}
     
    	public void onStartup() throws Exception
    	{
    		running = true;
    		thread.start();
    	}
     
    	public void onShutdown() throws Exception
    	{
    		running = false;
    		thread.join();
    	}
     
    	@Override
    	public void run()
    	{
    		while(running)
    		{
    			//do things that are fun and useful 
    		}
    	}
    }


  2. #2
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: Stop a thread?

    You can "stop" thread by calling Thread.interrupt. Also, if you do want such a functionality, your while loop should look like while(!Thread.isInterrupted()). Or you should perform such check-ups in some other place regularly. And you cannot restart thread that was interrupted. Consider using Runnable if you want to start a similar thread in future.

Similar Threads

  1. Java problem. Thread wont stop(FIXED)
    By albin1228 in forum What's Wrong With My Code?
    Replies: 21
    Last Post: February 17th, 2013, 03:42 AM
  2. Replies: 4
    Last Post: June 15th, 2012, 01:50 PM
  3. How to Stop a Thread Safley
    By viper_07 in forum Threads
    Replies: 4
    Last Post: July 17th, 2011, 05:26 PM
  4. Replies: 4
    Last Post: April 27th, 2010, 01:18 AM