joasisk
joasisk

Reputation: 61

Java thread loop stucks program

Hi I am doing a rather simple "karaoke" program... I'm trying to change shown text with a java Thread that starts on mouse click. When there is no loop and i click the mouse repetitively it works but When I add the infinite while loop into thread.run() it becomes stuck... it does nothing... what am I doing wrong? here is my code:

public class Timer extends Thread {
MainWindow window;
public int timeSec;
ArrayList<Integer> times;
public Song song;

public Timer(MainWindow window){
    times = new ArrayList<Integer>();
    times.add(10);      // de alto
    times.add(50);      // el carino
    times.add(70);      // cuando juanita 
    times.add(92);      // Limpia el
    times.add(113);     // de alto
    times.add(160);     // sabes
    times.add(215);     // la cosa esta + o.J
    times.add(226);     // mira
    times.add(244);     // ref
    times.add(266);     // matus
    times.add(272);     // Janka + krik
    times.add(293);     // mira

    song = new Song();
    this.window = window;
    timeSec = 0;
    //run();
}

public void start(){
    run();
}

public void run(){
    while (true){
        try {
            sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        timeSec++;
        if (times.contains(timeSec)){
            song.next();
        }
        window.repaint();

    }
} 
}

Upvotes: 0

Views: 270

Answers (2)

piet.t
piet.t

Reputation: 11911

Nikolay Ivanov already posted the answer, I'll try to add some context:

In the Thread class all code that actually creates a new native thread is called from the start()-method. Your own implementation for start() hides the one in Thread and does not call it via super() - so it is basically just like any other method you might implement and does not do any thread-creation. As a result your infinite loop is run on the main-thread (or the EDT in swing) and thus freezes your application.

So the best way really is not to mess around inside the Thread-class. Instead create a Runnable, pass it to a Thread-constructor and start() the thread - way less possibilities to do things wrong.

Upvotes: 0

Nikolay Ivanov
Nikolay Ivanov

Reputation: 8935

You've override start() method of Thread. So once you call start() no actual thread are spawn. See how to override thread.start() method in java?.

Upvotes: 6

Related Questions