How can I call and run a method on the main thread, called from its worker thread?
Main Thread code, (Foo() function is accessible from Main Thread):
Thread newThread = new Thread(myThread, myThread.getThreadName());
newThread.start();
Worker Thread code (newThread):
#Override
public void run(){
// need to call from here Foo() function - it has to run on the main thread
}
Thanks!
The words "call a method in another thread" have no meaning in Java.
You need to understand that Thread and thread are two different things: A thread is a path of execution through some code. A Thread is a Java object that can be used to start a new thread and manage its life cycle.
A new thread begins when some other thread calls t.start() where t refers to a Thread object. The thread begins executing the t.run() method, and it wanders into and out of function calls until it reaches the end of t.run(), at which point it dies. Meanwhile, other threads are following their own paths through the code.
At the lowest level, the only way for one thread to interact with another is by updating the fields of shared objects and classes.
Thread A can tell thread B to execute some function or another by sending a message (i.e., by updating a field in some object), but thread A can never make thread B do something. Thread B can only do what the code it is executing says to do. If the code says, look at field f, and if its value greater than zero, then call function foobar(), then that is what thread B will do. Or if the code tells it to pop a Runnable off of a queue and call the Runnable's run() method, then that is what the thread will do.
But no thread can change the code that some other thread is running once the thread starts running it. It can only change fields that influence what the code will do next.
Related
I read this statement:
The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.
Is it true?
I also came to know "Even if the main thread dies, the program keeps running".
This is my current understanding:
When you start a program, the JVM creates one thread to run your program.
The JVM creates one user thread for running a program. This thread is called main thread.
The main method of the class is called from the main thread.
If a program spawns new threads from the main thread, the program waits until the last thread dies.
Which one is true?
The program terminates when all non-daemon threads die (a daemon thread is a thread marked with setDaemon(true); it's usually used for utility threads). From the documentation:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
I read this statement: “The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.”Is it true?
No, it is not. The virtual machine terminates if the last non-daemon thread has finished. It doesn't have to be the main thread.
Simple example:
public static void main(String[] args) {
System.out.println("Main thread started");
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Second thread started");
try {
Thread.sleep(2000); // wait two seconds
} catch(Exception e){}
System.out.println("Second thread (almost) finished");
}
}).start();
System.out.println("Main thread (almost) finished");
}
When the main thread stops, the program terminates.
The program terminates when there no longer is any non-daemon thread running (or someone called System.exit). The main thread can have finished long ago.
The JVM will exit when the main thread and all non-daemon threads finish execution.
When you create a new thread, you can call Thread.setDaemon(true) to make it a daemon thread. If you do this, then the JVM will not wait until this thread finishes before execution. This is useful for any threads you create which are made to run in the background until the program stops.
If you create a new thread and do not call Thread.setDaemon(true), then the JVM will delay exit until this thread is complete, even if the main thread is finished.
When the main thread was start it'll not wait for the another thread which was created by us until they if can't use the join() of the thread class to wait for this thread. So basically if the child thread or sub thread getting more time for processing the task and you don't use the join() then main thread may be stop. To keep with main thread you must use the join() so the main thread stop after only this related thread are stop
check this link
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join%28%29
The first statementis not exact.
The java program terminates when all non-daemon threads has been terminated or when System.exit() or Runtime.exit() is invoked.
Thread is terminated when it exited its run() method. Main thread is special because you do not explicitly implement its run() method, you implement main() instead and the main() is called from run(). So, main thread is terminated when main() is terminated.
But main thread is not neccessarely the last one.
This is the from the JVM specification 3rd Draft, so it's the most current I'm aware of:
5.7 Virtual Machine Exit
The Java virtual machine terminates all its activity and exits when either:
• All threads that are not daemon threads terminate.
• Some thread invokes the exit method of class Runtime or class System, and
the exit operation is permitted by the security manager.
There is no distinction made about the main thread, so we shouldn't assume that is the only one that it applies to.
which is the thread that will begin as soon as the execution of a java program begins?
This was asked in an interview for me.
so can anyone suggest the answer here
From Thread API document
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).
And this thread will be called as main thread.
The thread which is created when you start is called the main thread. It is the one which invokes the main method.
Edit: apparently someone beat me to the answer.
The 'main()' method in Java is referred to the thread that is running,
whenever a Java program runs. It calls the main thread because it is
the first thread that starts running when a program begins. Other
threads can be spawned from this main thread. The main thread must be
the last thread in the program to end. When the main thread stops, the
program stops running.
Main thread is created automatically, but it can be controlled by the
program by using a Thread object. The Thread object will hold the
reference of the main thread with the help of currentThread() method
of the Thread class.
for more details check this link
'Main' Thread in Java
Can some body help me to understand my below questions:-
When new stack is created? On executing Thread t=new Thread() or t.start()
How start() method calls implemented run()?
Can we assign memory to each thread like JVM? If NO, how JVM will modify stack memory of running thread.
From the Javadoc of Thread:
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
Now, to your questions.
When [is a] new stack is created? On executing Thread t=new Thread() or t.start()?
A new thread is created by the constructor. It is run with the start method.
How [does] start() method calls implemented run()?
From the source code of Thread:
public void run() {
if (target != null) {
target.run();
}
}
Can we assign memory to each thread like JVM? If No, how JVM will modify stack memory of running thread.
No, you cannot assign memory to each thread. The operating system (Windows, Unix, OS X) controls how threads are created and destroyed. The JVM has access to every thread through a string identifier.
You can read the Thread source code for more information about the Thread class.
The Stack is created while the Start() method is called as till then the required info to create
the stack is not available.
The Thread class you call has this coded behind that calls run within its start method.
[In fact it is the Start() method that actually creates a new thread (not Thread class but the
real process thrad) and calls run() in the new thread. for eg: if you call run() instead of start
() in your runnable class. No new thread will be created.]
No. We cant assign Specific amount of memory to a thread.
Why do we need to run the thread through start method and not directly through the run method ?
The run method just executes the thread's task in the current thread. Historically, you would subclass Thread and override run - although today the preferred mechanism is to pass the Thread constructor a Runnable. So run itself doesn't do any threading - it's start which creates a new "actual" thread (as opposed to just a Thread object) and makes it execute run() when it's started.
Because the run method contains the code that the new thread should execute.
If you were to call the run method, then you'd just execute it on the current thread.
Calling start starts the new thread and then executes the run method on the new thread.
The start() method tells the JVM that it needs to create a system specific thread. After creating the system resource, it passes the Runnable object to it to execute its run() method. Calling the run() method directly has the "Thread" execute in the same thread as the calling object, not in a separate thread of execution, as intended.
In other words, calling run() is just like a normal method call. Whereas, calling start() tells the thread to create the necessary system resources and then execute the run() method asynchronously.
EDIT:
For example,
Pseudo code1:
thread one = new thread();
thread two = new thread();
one.run();
two.run();
This makes the threads run sequentially,ie, two.run(); will run only after one.run(); finishes.
Pseudo code2:
thread one = new thread();
thread two = new thread();
one.start();
two.start();
In this case both threads start and run simultaneously.
The start() method calls the run() method asynchronously (doesnt waits for any result, just fires up an action), but when WE call run(), it runs synchronously, ie,it waits until run() finishes and only then it proceeds to the next line of code.
in java Thread is always created in Stack Memory.When you create a new Thread it takes new memory in Stack.When you call start() method it initialize in new Stack Memory and when you call run() method it initialize in same Stack Memory
That is why we always call a Thread with start() method
in the main method if I write this:
Thread aThread = new Thread();
aThread.run();
what will happen???
It will run in current thread. You will not start new thread this way.
But that doesn't really matter in your example since you gave new Thread no code to run anyway.
The thread that runs the main() code is the current thread. Creating a Thread object and calling one of its methods (other than start()) is like calling a method of class Integer or String - it doesn't create a new actual thread.
In your code example, execution of the main method will continue only when the run() method has finished running. This means that if the run() method has an endless loop (let's say it's waiting for incoming requests), then the main() method will never continue running, even if there are more lines of code after the call to run().
Calling aThread.start() creates a new actual thread (represented by the object aThread), makes the new thread call the run() method, and returns execution of the original thread to the next line in the main(). This means that the new thread can run around in circles forever, but it doesn't stop the main() code from creating more threads or performing other tasks.
It will just run like you're calling a normal method. So the method will be running in the same thread that calls the method.
It will run in the current Thread not in new Thread So If you call run method yourself it is meaningless. Because It doesn't create a new Thread.
If you call the start-method on a Thread class, the start-method will return after a while, but in concurrency will run the content of the run-method. If you call the run-method directly it will be executed and return to the caller, after the method is completely done - as every normal method call.