Getting control back to main program in java while using thread - java

I'm invoking thread.In that thread there is while(true) condition because of that I'm not able to execute next thread.
Snippet is here
ASubscriber aSubscriber=new ASubscriber();
aSubscriber.run();
System.out.println("Starting Subscriber Thread");
BSubscriber bSubscriber=new BSubscriber();
bSubscriber.run();
In each of run method of ASubscriber and Bsubscriber has below Code :
#Override
public void run() {
while (true)
{
//I'm going some task
}
}

aSubscriber.run();
System.out.println("Starting Subscriber Thread");
Thread#run does not start threads.
It just runs them on the current thread.
You probably want
aSubscriber.start();

Related

IllegalThreadStateException on Thread.interrupt

I have a java program, which takes very long time to compile.
For testing purposes, I want to kill the program and restart it if compilation takes long duration.
Here is the simplified version of my code:
public class Main {
public static void main(String[] args) {
Thread foo = new Thread(new Foo());
while (true) {
foo.start();
while (true) {
if (needRestart()) {
foo.interrupt();
break;
}
}
}
}
}
foo.java looks a bit like this:
public class Foo implements Runnable {
// some code
public void run () {
try {
while (!Thread.currentThread().isInterrupted()) {
// some code
}
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
The problem is that the program crashes and throws an IllegalThreadStateException
If you need the full code, here it is: full code
Don't start foo thread in while(true) loop. You can start a Thread only once in it's life cycle.
Move foo.start(); above while(true)
Refer to oracle documentation page about Thread class start() method
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
IllegalThreadStateException occurs when you try to change the state of your thread or when you try to again calling the start method on same thread once it is in running state.
But in your case if you want to interrupt your thread make it to go to sleep() in and when you want you to interrupt call notify() on that thread before it comes out of sleep automatically.

Why is this thread affecting the main thread?

I must be missing something:
public class Test {
public static void main(String[] args) {
(new Thread(new Action())).run();
System.out.println("Blah");
}
}
class Action implements Runnable {
public void run() {
while (true) {
}
}
}
I make a thread that is supposed to be running a loop.
In my main thread I print "Blah".
However, it is never printed. Why not? If I made a separate thread, it shouldn't affect my main execution thread, right?
This machine has four cores.
Call start() instead of run() to start a thread.
Simply calling run() means a method call with infinite loop in the same main thread that will block the next statement written in main thread.
Have a look at Java Tutorial on Defining and Starting a Thread
I should be (new Thread(new Action())).start(); to start a thread but still it will create an infinite loop and the new started thread will never stop.
Try with Thread.currentThread().getName() to confirm it again as shown below:
public void run() {
System.out.println(Thread.currentThread().getName()); // output "main"
}
A Pictorial Representation of Thread Life-cycle along with it's methods
Because you are not invoking start(), you are calling directly the implementation method of the thread run(), thus no thread is started, code is just executed.
run() is the method called by the thread internal structure to execute the task, since it's just a normal method which doesn't have anything attached.

Thread Runnable - stop and resume

Hello i'm new in Android(Java), and i have a problem with the use of thread
I define e new Thread timed (every 5 seconds) inside a class of my android Project.
The "mContinueThread" variable is used to cicle every 5 seconds
r = new Runnable() {
public void run() {
while (mContinueThread) {
try {
Thread.sleep(MILLISEC_BEFORE_RELOAD);
mHandler.sendEmptyMessage(GET_TRACKING);
}
catch (Exception e)
{
}
}
}
};
t = new Thread(r);
In the CLass there is a method StartTrack() that starts with Thread
public void StartTrack()
{
mContinueThread=true;
if (!mThreadIsStarted)
{
mThreadIsStarted=true;
t.start();
}
else
{
}
}
and there is also a method Logout that stop the thread, using the "mContinueThread" variable:
public void LogOut()
{
//STOP THREAD
mContinueThread=false;
....
}
If in the class Logout() method is executed the thread is stopped, but if the StartTrack() method is called again I don't know how to restart the execution of the thread.
Can you Help Me?
You can use AsyncTask in Android. This will get rid of the burden of managing the threads manually. Please visit http://developer.android.com/reference/android/os/AsyncTask.html
You cannot re-start a thread. Once thread is finished execution it will reach the DEAD state. And whatever is DEAD cannot be brought back to life again, neither in real world nor in JAVA world.
You have no way to restart a thread as long as it exited. You can just start a new start.
I solved so:
In my class I just define the Runnable object, but not the new Thread.
In the StartTrack method(), if the thread has not yet been instantiated, I create and start
public void StartTrack()
{
mContinueThread=true;
if (!mThreadIsStarted)
{
mThreadIsStarted=true;
t = new Thread(r);
t.start();
}
}
In the "LogOut()" method, if Thread is started, I Stop It, and I set It to Null.
In this way, at the next call of "StartTrack()" method, I can recreate it again
public void LogOut()
{
mContinueThread=false;
if (mThreadIsStarted)
{
//THREAD STOP
mContinueThread=false;
mThreadIsStarted=false;
//THREAD TO NULL
t=null;
}
...
}
I suggest it's better to use something like Timer instead of thread.
http://developer.android.com/reference/java/util/Timer.html
Then you can do cancel() if you want to stop execution of your task
and resume it by scheduling new one.

Java, main code stops when the thread is started

When i start some thread in my program, everything else is stopped.
This is my Thread code...
static Thread b1 = new Thread(new Builders());
b1.run();
System.out.println("done");
This is the class Builders.
public class Builders implements Runnable {
static boolean busy=false;
Random r = new Random();
public void run() {
try{
busy=true;
System.out.println("ready");
Thread.sleep(9999);
busy=false;
System.out.println("done");
}
catch(Exception e){
}
}
}
When I run the program , the thread is started and the program wait for the end of the thread. I thought the main point of the threads is that the code can run simultaneously. Could someone please help me understand what I'm doing wrong.
That's because threads are started with start(), not run(), which simply calls the run method on the current thread. So it should be:
static Thread b1 = new Thread(new Builders());
b1.start();
System.out.println("done");
This is because you are not starting a thread - instead, you are executing thread's code synchronously by calling run(); you need to call start() instead.
Better yet, you should use executors.
You need to call the start() method. The internal code of Thread will start a new operating system thread that calls your run() method. By calling run() yourself, you're skipping the thread-allocation code, and just running it in your current Thread.

Do I have to manually stop threads in Java?

When my application is ready to exit, either by closing a window or invoking the System.exit() method. Do I have to manually stop the threads I may have created or will Java take care of that for me?
In cases you use System.exit(). All the threads will stop whether or not they are daemon.
Otherwise, the JVM will automatically stop all threads that are daemon threads set by Thread.setDaemon(true). In other words, the jvm will only exit when only threads remaining are all daemon threads or no threads at all.
Consider the example below, it will continue to run even after the main method returns.
but if you set it to daemon, it will terminate when the main method (the main thread) terminates.
public class Test {
public static void main(String[] arg) throws Throwable {
Thread t = new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(300);
System.out.println("Woken up after 300ms");
}catch(Exception e) {}
}
}
};
// t.setDaemon(true); // will make this thread daemon
t.start();
System.exit(0); // this will stop all threads whether are not they are daemon
System.out.println("main method returning...");
}
}
If you want stop threads before exit gracefully, Shutdown Hooks may be a choice.
looks like:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
//Stop threads }
});
See: hook-design

Categories

Resources