Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java - Countdown using Thread problem

countdown using thread

  • Please log in to reply
15 replies to this topic

#13 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 17 February 2011 - 11:08 AM

If you want to "kill" a thread, you must make sure it reaches the end of its run method.
I usually make a Runnable class like so:

public class MyClass implements Runnable(){
  private boolean run;

  public MyClass(){
    run = true;
  }

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

  public void stop(){
    run = false;
  }
}
In your case (taking the public void run from your previous code), this would change into
public class X implements Runnable{
private boolean run;
private int c;

public void run() {
   c = 5; 
   while (c > 0 [B][COLOR="red"]&& run[/COLOR][/B]) {
      --c;
     try {
        Thread.sleep(1000);
     } catch (InterruptedException x) {
     }
     label.setText("Time: " + c);
   }
}

public void stop(){
   run = false;
}

public int getTimeLef(){
   return c;
}
}

  • 0

#14 Serialcek

Serialcek

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 151 posts

Posted 17 February 2011 - 12:44 PM

Hmm ok now I understand I little bit more about threads but still isn't working as it has too
As you said I change my method in this:

class RCountDown implements Runnable {

		private boolean run;
		private int c;

		public void run() {
			c = 6;
			run = true;
			while (c > 0 && run) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException x) {
				}
				Cas_desni.setText("Čas: " + c--);
			}
		}

		public void stop() {
			run = false;
		}

		public int getTimeLeft() {
			return c;
		}

	}

Ok explain me something.. when I start this Thread the first method wich is called is run(); and then stop(); is this true?
What does the method return getTimeleft... in return c to what? I don't understand.

Any way I change this:

if (answer == correct){    // Pseudo-code
(new Thread(new RCountDown())).destroy();  
(new Thread(new RCountDown())).start();
}

into this:

if(answee==corect)
	(new Thread(new LCountDown())).interrupt();
			(new Thread(new LCountDown())).start();

Now it working a litle bit better but my precedent Thread didn't end but te two threads run together.
If I use System.print it looks like:

Time: 5 //first thread start
Time: 4
Time: 3
Time: 5 // now it should kill the precedent and the new one should start
Time: 2 //but the two threads just go
Time: 4
Time: 1
Time: 3
Time: 0
Time: 2
Time: 1
Time: 0
  • 0

#15 Serialcek

Serialcek

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 151 posts

Posted 20 February 2011 - 12:17 PM

So I found one solution to my problem but it sucks.. :)
My solution consist in this that for one countdown timer I have to do 2 countdown classes.

Runnable Rrunnable = new RCountDown();
Thread Rcount = new Thread(Rrunnable);

Runnable Rrunnable2 = new RCountDown2();
Thread Rcount2 = new Thread(Rrunnable);

This 2 threads do the same thing but if I stop and start the same thread I recevie an error

For now my solution works like this:
if(answee==correct)
Rcount.stop();	
Rcount2.start();	

Is there any to do that without having a second thread (in this case Rcount2)

I guess it hits me an error because thread Rcount is still alive.. and I check it with this
if(answer == correct){
	Rcount.stop();		
			if(Rcount.isAlive()== true){
			System.out.print("Is alive");
			}
			}

  • 0

#16 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 21 February 2011 - 11:14 AM

I think this is one of the most simple implementations of a countdown thingy with a thread and runnable.

Counter class (I tried to stay as close to your original as possible)
public class Counter implements Runnable {
    private boolean run;
    private int c;
    private JLabel label;

    public Counter(JLabel label) {
        c=6;
        this.label = label;
    }

    public void run() {
        run = true;
        while (c > 0 && run) {
            c--;
            label.setText("time left: " + c + "s.");
            System.out.println(c);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException x) {
            }
        }
    }

    public void stop() {
        run = false;
    }

    public void setTimeLeft(int seconds) {
        this.c = seconds;
    }
}
CountDown class:
import javax.swing.*;

public class CountDown {
    private Counter counter;
    private Thread thread;

    public CountDown(JLabel label) {
        counter = new Counter(label);
    }

    public void restart() {
        counter.stop();
        counter.setTimeLeft(6);
        thread = new Thread(counter);
        thread.start();
    }

    public void start() {
        counter.stop();
        thread = new Thread(counter);
        thread.start();
    }

    public void stop() {
        counter.stop();
    }
}
So far the code you should be able to understand, the next code is just a small Gui to see it happen:

Gui class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Gui extends JFrame {
    private CountDown countDown;

    public Gui() {
        super("frame");
        JLabel label = new JLabel();
        countDown = new CountDown(label);

        JButton start = new JButton("start");
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                countDown.start();
            }
        });

        JButton stop = new JButton("stop");
        stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                countDown.stop();
            }
        });

        JButton restart = new JButton("restart");
        restart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                countDown.restart();
            }
        });

        JPanel southPanel = new JPanel();
        southPanel.add(start);
        southPanel.add(stop);
        southPanel.add(restart);

        add(label, BorderLayout.CENTER);
        add(southPanel, BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,100);
        setVisible(true);
    }

    public static void main(String[] args) {
        Gui gui = new Gui();
    }
}

I hope this helps.
  • 0





Also tagged with one or more of these keywords: countdown, using thread

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download