Thread and public void run() method in java [duplicate] - java

This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 9 years ago.
public Thread thread = new Thread();
public void start() {
running = true;
thread.start();
}
public void run() {
while(running) {
System.out.println("test");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
My problem is that the program will not print out "test" nor will it seem to loop despite 'running' being true. Is there a way I can continuously loop in the run method?

You haven't actually asked run() to be called. All you've done is declare a run() method unrelated to the Thread.
Put your run() method in a Runnable and pass that to the Thread.
public Thread thread = new Thread(new Runnable() {
public void run() {
while (running) {
System.out.println("test");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

The problem appears to be that you aren't running the run method that you think you're running in the thread.
First, you've created a Thread called thread. In your class's start method, you set running to true and call thread.start(). But that just calls Thread's run() method, which does nothing.
public void run()
If this thread was constructed using a separate
Runnable run object, then that Runnable object's run method is called;
otherwise, this method does nothing and returns.
You aren't calling your own run method.
You have created a run method. I can't see your class definition here, but I'm assuming that your class implements Runnable. You need to send an instance of your class as an argument to the Thread, by using the Thread constructor that takes a Runnable. Then the Thread will know to run your Runnable's run() method.

Well you need to call start() to start the thread. Otherwise neither running will be true
nor thread.start() get executed. Well i can guess you were intended to do something like this:
class MyTask implements Runnable
{
boolean running = false;
public void start() {
running = true;
new Thread(this).start();
}
public void run() {
while(running) {
System.out.println("test");
try {
Thread.sleep(1000);
// you were doing thread.sleep()! sleep is a static function
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new MyTask().start();
}
}

Related

Thread not executing [duplicate]

This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 5 years ago.
This thread does not execute when I run the program. I'm wondering if there's something wrong with the code.
public static void writeToFileAsync(final String saveState, final String fileName) {
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
start();
}
};
}
Also, why does NetBeans want me to put that semicolon next to the second curly brace after the start() call?
Start a thread
Your thread will only start if you call the start method explicitly. Here is the documentation Thread#start. The start method will then internally invoke the run method of your Thread.
Your code could then look like this:
public static void writeToFileAsync(final String saveState, final String fileName) {
// Create the thread
Thread fileWriter = new Thread() {
#Override
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
// Do nothing
}
}
};
// Start the thread
fileWriter.start();
}
And you probably want to remove the start(); call inside your run method.
Semicolon
You need the ; after the Thread creation because you are using an assignment:
Thread fileWriter = new Thread() { ... };
The concept you are using here is called anonymous class. Basically it is the same as if creating a new class like:
public class FileWriter extends Thread {
#Override
public void run() {
...
}
}
And then using it like:
Thread fileWriter = new FileWriter();
However an important difference is that your anonymous class has access to your local variables (the scope of that method). And that it is anonymous, so it's like a small single-time usage class.
Your call to the start method cannot be inside the body of your thread. You can do this:
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
}
}.start(); // call the start method outside the body of you thread.
And about the semicolon, you are creating an Anonymous Class and that is its syntax:
Because an anonymous class definition is an expression, it must be
part of a statement... (This explains why there is a semicolon after
the closing brace.)
A thread simply works this way. Below is a piece of code where a thread is created as an anonymous inner type where the run method is overrided. Then by calling the start method , it automatically called the overrided run method.
public class ThreadTest {
Thread t = new Thread(){
public void run() {
System.out.println("thread is running");
};
};
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.t.start();
}
}

How to stop execution of method called from run() method of thread

Here is my Thread:-
Thread t=new Thread(){
public void run(){
downloadFile();
}
}
t.start();
public static void main(){
t.interrupt();
}
Here downloadFile() is long running method (downloading file from server)
The issue is , even though t.interrupt() is called downloadFile() method still keeps running which is not expected . I want downloadFile() method to terminate immediately as soon as the thread is interrupted. How should i achieve it ?
Thanks.
EDIT1:
Here is downloadFile() skeleton which calls the rest API to fetch file:
void downloadFile(){
String url="https//:fileserver/getFile"
//code to getFile method
}
Your Runnable needs to store an AtomicBoolean flag to say whether it has been interrupted or not.
The interrupt method should just set the flag to true.
The downloadFile() method needs to check the flag inside the download loop and abort the download if it is set.
Something like this is the only clean way to implement it as only downloadFile knows how to safely and cleanly interrupt itself, closing sockets etc.
You need some flag to inform a thread about termination:
public class FileDownloader implements Runnable {
private volatile boolean running = true;
public void terminate() {
running = false;
}
#Override
public void run() {
while (running) {
try {
downloadFile();
} catch (InterruptedException e) {
running = false;
}
}
}
}
in main:
FileDownloader fileDownloaderRunnable = new FileDownloader();
Thread thread = new Thread(fileDownloaderRunnable);
thread.start();
//terminating thread
fileDownloaderRunnable.terminate();
thread.join();

child thread blocks parent thread in java

public static void main(String[] args) throws Exception {
new Thread(new Runnable() {
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello");
}
}
}).run();
System.out.println("Bye");
}
In the main thead, I create a new thread, which will print "hello" every second. Why the final "Bye" never got print? In the other word, why the child thread blocks the main thread?
Because you are calling run(), instead of start().
You must never call run() directly. If you call start(), the program will call run() for you, in a different thread. (Like you wanted.) By calling run() yourself, you are going into the run() method with the parent thread, and get stuck in an eternal loop, with your parent thread.

Calling non thread class from thread

My Problem:
I want to run a method from a Thread, which is no Thread but might take some time to execute (e.g. waiting for server response). It is important that my none thread method is in another class (the classes are Objects which are used in other classes too).
If you do this as in the example code, the whole program will pause for 10 seconds, but I want it to continue with other program code.
Is there a good way of doing this?
My code:
MyThread.java (extends Thread)
public Foo foo;
public void run() {
foo.bar();
}
Foo.java
public void bar() {
try {
Thread.sleep(10000);
// Represents other code that takes some time to execute
// (e.g. waiting for server response)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And a main method:
public static void main(String[] args) {
MyThread t = new MyThread();
t.foo = new Foo();
System.out.println("Starting!");
t.run();
System.out.println("Done!");
}
You don't want to call run() on the Thread, you want to call start().
Assuming MyThread extends Thread, you need to call start() not run().
Calling run() is just calling a method synchronously.
public static void main(String[] args) {
MyThread t = new MyThread();
t.foo = new Foo();
System.out.println("Starting!");
t.start(); // change here
System.out.println("Done!");
}
start() actually starts an OS thread to run your code on.
Use start() rather than run() on your thread. Or else it will be just like the main thread calling a method of another thread which means you are calling wait() on the main thread itself.
don't call run() method directly.
call start() method instead of run() method.
when call run() method directly
this thread go to main stack, and it run one by one.
class MyThread extends Thread{
public Foo foo;
public void run() {
foo.bar();
}
}
class Foo{
public void bar() {
try {
boolean responseCompleted = false;
boolean oneTimeExcution = false;
while(!responseCompleted){
if(!oneTimeExcution){
// Represents other code that takes some time to execute
oneTimeExcution = true;
}
if( your server response completed){
responseCompleted = true;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
System.out.println("Starting!");
t.start();
System.out.println("Done!");
}

Do non synchronized methods block when a synchronized one is executing

The following code blocks in synchronized sync() method before calling plain() method. Why is this so, shouldn’t the intrinsic lock block call to synchronized methods only – for example this behavior would have been fine if plain() was synchronized as well.
As the monitor concept that java uses is applicable to synchronized methods/blocks only – it by definition should not affect execution of non synchronized code. Is this always the case or is this behavior JVM implementation specific.
public class Main {
public static void main(final String[] args) {
final Main main = new Main();
new Thread(new Runnable() {
#Override
public void run() {
main.sync();
}
}).run();
main.plain();
}
public synchronized void sync() {
try {
System.out.println("sleeping...");
Thread.sleep(2000);
System.out.println("out...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void plain() {
System.out.println("plain...");
}
}
Output:
sleeping...
out...
plain...
You should call start() rather than run() on the new Thread. Calling run() will execute the runnable's run method in the current thread, rather than starting a new thread to run it.

Categories

Resources