user2612619
user2612619

Reputation: 1129

Program not executing thread

So I have two files, the first is a swing class and the second is my thread class. When I run my thread for for some reason it doesn't run, I tried by placing some print statements to see if my program would ever get there but none of them ran.

My thread class

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class CheckFiles implements Runnable {

    public void run() {

        while (!UserInterface.stop) {
            try {

                String line;

                BufferedReader b = new BufferedReader(new FileReader(UserInterface.location));

                while((line = b.readLine()) != null) {

                    System.out.println(line);

                }

            } catch (IOException e) { System.out.println(e); }
        }
    }
}

In my UserInterface class I start the method by doing the following

System.out.println(stop); //prints true
loadFile.setEnabled(false); //not important
status.setText("Checking Files"); //not important
stop = false; 
System.out.println(stop); //prints false
new CheckFiles(); //start thread

Is there something that is stopping my thread from running or am I doing it wrong?

Upvotes: 2

Views: 82

Answers (4)

APerson
APerson

Reputation: 712

You just have created an instance of the class that is supposed to be a Thread! You have to actually declare a Thread and start it. e.g. new Thread(new CheckFiles()).start(); to create an instance of the thread, the object and start it.

Upvotes: 1

igleyy
igleyy

Reputation: 605

At the moment you only made your class Runnable. You need to create and start your thread. Please take a look at http://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html.

Thread t = new Thread(new CheckFiles());
t.start();

The main differences between extending Thread, and implementing your target Runnable is that when extending Thread you are associating the Thread with the object you are creating. By making your Object runnable, you are able to associate your Thread with many runnable objects..

Upvotes: 1

Ulbo
Ulbo

Reputation: 346

You should'nt make the class extend thread, rather do something like

Thread t = new Thread(new CheckFiles());
t.start();

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

You are creating a class that can be used to start a thread, but you are not starting it.

Several solutions are possible:

Solution 1:

Change the type to extend Thread

class CheckFiles extends Thread {
    ...
}

and change the last line to

(new CheckFiles()).start();

Solution 2:

Keep CheckFiles a Runnable, and change the last line to

(new Thread(new CheckFiles())).start();

Upvotes: 2

Related Questions