Program not executing thread - java

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?

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();

You should'nt make the class extend thread, rather do something like
Thread t = new Thread(new CheckFiles());
t.start();

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..

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.

Related

Why does one thread stop the other thread from running?

I was going to use threads for each sound in a game engine I'm making. The problem is, whenever I make a new thread that has a while(true) statement, the other thread stops running.
I made a class to test this, and it only prints "goodbye", not "hello". I was wondering how to make the two threads run at the same time.
public class testor {
public static void main(String args[]){
testor test=new testor();
test.runTest();
}
class threadTest implements Runnable{
#Override
public void run() {
while(true){
System.out.println("goodbye");
}
}
}
public void runTest(){
threadTest test=new threadTest();
test.run();
while(true){
System.out.println("hello");
}
}
}
Since you are doing test.run(); you are only calling the method of that class but not starting the thread.
So in order to answer your question: there is no such a thread stopping the other thread from running? because you have only one Thread that is looping for ever and printing the message System.out.println("goodbye");
If that method is not looping for ever, it would return to the runTest method and then you would see the System.out.println("hello");
Summary:
For starting a Thread use the Thread::start method and not the run.
Using (new ThreadTest()).run() does not start a new Thread, but just invokes the run() method in the current thread.
To run the code in a separate thread do:
(new Thread(new ThreadTest())).start();
That's because you're not creating a new thread. Just naming a class something containing "thread" will not make it a thread, and a Runnable is no thread - it's a class like any other, with no special semantics or behaviour.
It's only special in that you can pass it to a Thread for execution.
public class Testor {
public static void main(String args[]){
Testor test=new Testor();
test.runTest();
}
class MyRunnable implements Runnable{
#Override
public void run() {
while(true){
System.out.println("goodbye");
}
}
}
public void runTest(){
Thread testThread = new Thread(new MyRunnable());
testThread.start();
while(true){
System.out.println("hello");
}
}
}
You should probably also adhere to the Java coding standards regarding your class and variable names if you do not want your code to look like an alien when combined with most other existing Java code.
Additionally, multithreading is more than just being able to start a new thread. You should also read about synchronisation issues - it's more complicated to do correctly than you might imagine.
Your run method contains an infinite loop.
The runTest() method creates the thread which means you'll have 2 execution stacks the main stack, and the runnable threadTest stack.
since you're running the thread method first that contains an infinite loop, you'll always get the output "good Bye".
Remove the infinite loop from run() method.

Java Get multiple threads of different classes to run concurrently

Im not sure exactly what the problem is but for some reason I cant get threads from two classes to run at the same time. I can get multiple threads from one class to run at the same time, but when I try to start another class nothing happens.
public professor(){
prof = new Thread();
prof.start();
System.out.println("Prof has started1");
}
public void run(){
try{
System.out.println("Prof has started2");
prof.sleep(600);
//do more stuff
}
catch(Exception e){
System.out.println("Prof error");
}
This is how I started my second class, the first one is started in the exact same way and runs fine. With this class however "Prof has started1" gets displayed, but the second one never does.
Am I missing something?
I think this is the reason
prof = new Thread();
prof.start();
This code will never call your own run() method, if your class implements the runnable interface, you should do this
prof = new Thread(this)
prof.start()`
You don't provide the full delcartion the Professor class so the exact solution may vary but the main point that I see is this: you create an instance of the Thread class and then invoke .start():
prof = new Thread();
prof.start()
Alas, the Thread class by itself does not do any thing when you call .start() on it. you need to tell it what is the action that you want it to carry out once it has been start()-ed. There are several ways to do so, but I will go with this:
public professor() {
prof = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Prof has started2");
Thread.currentThread().sleep(600);
//do more stuff
}
catch(Exception e){
System.out.println("Prof error");
}
}
});
prof.start();
System.out.println("Prof has started1");
}
public void run() {
}
That is: create an instance of Runnable in which you override the run() such that it does whatever you want it to do. Then pass this instance of Runnable to the constructor of the Thread object you're creating. When you subsequently invoke .start() the run() method of that Runnable will get executed.

Java: Thread.sleep() inside while loop not working

Alright, I'm new to threading, so my question might be pretty dumb. But what I want to ask is, I have this class, let's say its name is MyClass.java. And then inside one of its methods is callThread(), which I want to print something out, sleep, and return control to MyClass.java's method. How do I do that?
Currently, my code goes something like this:
class MyClass {
void method()
{
MyThread thread = new MyThread();
thread.run();
// do some other stuff here...
}
}
And then, this will be the MyThread:
class MyThread implements Runnable {
public void run()
{
while (true)
{
System.out.println("hi");
this.sleep(1000);
}
}
}
I was hoping that MyThread would print "hi", pass back control to MyClass, and then print "hi" again one second later. Instead, MyThread freezes up my entire program so having it in there doesn't work at all...
Is there any way around this?
You should be callig thread.start()
More on that in the manual: Defining and Starting a Thread
You must have to call start() method of Thread class.
MyThread thread = new MyThread();
Thread th=new Thread(thread);
th.start();
sleep() is an instance method of Thread class and MyThread class is not a thread (It's a runnable) so you need to use Thread.currentThread().sleep() method.
while (true)
{
System.out.println("hi");
try{
Thread.currentThread().sleep(1000);
}catch(Exception ex){ }
}
Read this tutorial for more info on thread.

Preventing other threads from running a piece of code

I want to prevent to other threads(illegal threads) from running run(). the solution is:
public class MyThread extends Thread {
public void run() {
if (currentThread() != this)
throw new IllegalStateException("Exception occurred by: " + currentThread().toString());
/* Here goes the main logic of thread */
}
}
How could we do the same thing when MyThread class is directly implementing Runnable?
Simply store a reference to the Thread that is allowed to run the code as a member in your Runnable class. Use that in the comparison.

Get all threads that run with a specified Runnable

I have one Runnable that is used by more than one thread:
Runnable myRunnable = new MyWorker();
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
How can I get all threads that are created with myRunnable?
(Of course the example is simplified. I create new threads with myRunnable on several places in different classes.)
Use case (as requested): MyWorkerOfMyPage is a delayed worker that is bound to a page. If the user leaves this page (e.g. by navigating to another page) all threads that belong to MyWorkerOfMyPage should be killed ungracefully as their result is not needed anymore.
As already said best way is to track this yourself. This forces you to get a clear understanding of what you are doing. A good thing if you work with threads ... hmmm ... a good thing in every case ;).
But if you realy want to detect the threads you can use reflection with the Thread class to get the required information. First make the method "getThreads" accessible to get all running Threads, then make the field "target" accessible to get the runnables of the Threads.
Heres an example program (but I would advise against the usage in a real application. You should now what threads you are starting, it might harm compability with future JDKs, might harm portability ...):
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Runnable myRunnable = new Runnable() {
#Override
public void run() {
try {
System.out.println("Start: " + Thread.currentThread().getName());
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
List<Thread> threads = getThreadsFor(myRunnable);
for (Thread thread : threads)
System.out.println("Found: " + thread.getName());
}
private static List<Thread> getThreadsFor(Runnable myRunnable) throws Exception {
Method getThreads = Thread.class.getDeclaredMethod("getThreads");
Field target = Thread.class.getDeclaredField("target");
target.setAccessible(true);
getThreads.setAccessible(true);
Thread[] threads = (Thread[]) getThreads.invoke(null);
List<Thread> result = new ArrayList<Thread>();
for (Thread thread : threads) {
Object runnable = target.get(thread);
if (runnable == myRunnable)
result.add(thread);
}
return result;
}
}
The best way to do this is to track this yourself. Use a global singleton for instance that launches the threads and track which ones you started.
Although my first thoughts are along #Bengt's lines, perhaps you could use Class.isAssignableFrom if you had a list of runnables and you just want to know which ones use your interface.
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html
In Java there is no simple way to find all the places a object is referenced, its something you have to maintain a collection of yourself.
If you want to know this staticly you can Find Usages in your ide.
If you want to know this dynamically you can have the Runnable add the Thread to a collection (and remove it when finished)
Generally speaking, the developer should only create Threads deliberately. i.e. the Developer should know when he/she is creating thread and what those threads will be doing. Its not something you should be trying to track at runtime if you have a good design.

Categories