When run() method execute in java thread? - java

I have a simple test with thread:
package Thread;
class Sum extends Thread {
int low, up, S;
public Sum(int a, int b) {
low = a;
up = b;
S = 0;
System.out.println("This is Thread " + this.getId());
}
#Override
public void run() {
for (int i = low; i < up; i++) {
S += i;
}
System.out.println(this.getId() + ":" + S);
}
}
public class Tester {
public static void main(String agrs[]) {
Sum T1 = new Sum(1, 100);
T1.start();
Sum T2 = new Sum(10, 100);
T2.start();
System.out.println("Main process terminated");
}
}
but i don't understand when was run() method executed, it return same that:
This is Thread 8
This is Thread 9
Main process terminated
9:4905
8:4950
It's mean the run() method was executed after T1 and T2 start. I still think that when start() method was invoked the run() will be execute. Thank for advance!

When you call start() on the thread object , it invokes the run() method.
When in doubt , read the documentation: Thread#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.
Suggested Reading:
Why we call Thread.start() method which in turns calls run method?
Oracle tutorial
Why is run() not immediately called when start() called on a thread object in java

The start() method creates a new thread, that executes the run() method.
From Documentation:
Causes this thread to begin execution; the Java Virtual
Machine calls the run method of this thread.

When we invoke Thread.start JVM creates a new native thread and then calls Thread.run which causes this Thread to begin execution. Thread.run is invoked by JVM asynchroneously, so these 3 lines
Main process terminated
9:4905
8:4950
might appear in any order.

The thread scheduler is selecting which thread for run. It can be random selection if you are not giving any priority for the thraed.
Here the thread scheduler will select thread and it will work in two separate stack space as two independent thread process. So thread T1 starts before thread T2 and there is no sleep, no wait, no join the both will give output at same time.
for more details please visit http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#start%28%29
you can understand it more clearly if you use remaining functions of Thread like sleep(), join(), wait() etc...

Related

Why wait method doesn't work on Thread object? [duplicate]

This question already has an answer here:
After executing wait(), how long does a thread wait if it does not get notified from other threads?
(1 answer)
Closed 2 years ago.
Thread t2 = new Thread();
Thread t3 = new Thread();
t1.start();
t2.start();
synchronized (t2) {
t2.wait(20000);
}
t3.start();
The above program runs without t2 waiting for 20sec. I observed that when thread object is started then it wont wait. Why is this happening?
Why is this happening?
First, let's be clear. This function call, t2.wait(20000) does not do anything to the t2 thread. In fact, it doesn't really do anything at all. All it does is not return until either one of two things happens;
Some other thread calls t2.notify(), or
20 seconds elapse.
If the call took less than 20 seconds to return, then that's probably because the t2 thread itself called t2.notify() just before it died. In most implementations of the Java standard library, the join() method is implemented by using wait() and notify() calls on the thread object.
(Note: most authors will advise you not to ever call wait() or notify() on a Thread instance precisely because of the potential for interference between your code and the library code when both call the same methods on the same instance.)
The above program runs without t2 waiting for 20sec.
As somebody else already has pointed out here, You have not provided any run() method for your t2 thread, so it's unclear why you would expect the t2 thread to "wait" or, to do anything else at all. The only thing a thread ever does is execute the code that you provide for it in a run() method.
The default Thread.run() method would call the run() method of a delegate object that you supply when you construct the threads, but your code supplies no delegate. In that case, the default run() method does nothing at all.
Use sleep to pause the thread regardless of having work to finish.
wait doesn't pause the thread, it just waits the thread to finish (and this thread already finished).
class SleepThread extends Thread {
//run method for thread
public void run() {
for(int i=1;i<5;i++) {
try {
//call sleep method of thread
Thread.sleep(20000);
}catch(InterruptedException e){
System.out.println(e);
}
//print current thread instance with loop variable
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
class Main{
public static void main(String args[]){
//create two thread instances
SleepThread thread_1 = new SleepThread();
SleepThread thread_2 = new SleepThread();
//start threads one by one
thread_1.start();
thread_2.start();
}
}
Thread sleep method in java

what happens if thread calls join() on itself

From what i read here Thread join on itself ;
When join method is called on itself, it should wait forever
I am currently preparing for ocajp 8 certification,for which going through dumps and when i got this question ,what i thought is main should wait forever
public class startinginconstructor extends Thread
{
private int x=2;
startinginconstructor()
{
start();
}
public static void main(String[] args) throws Exception
{
new startinginconstructor().makeitso();
}
public void makeitso() throws Exception
{
x=x-1;
System.out.println(Thread.currentThread().getName()+" about to call join ");
join();
System.out.println(Thread.currentThread().getName()+" makeitso completed ");
// above line shouldn't be executed (method shouldn't be completed as well )since it joined on itself..?
}
public void run()
{
System.out.println(Thread.currentThread().getName()+" run started ");
x*=2;
System.out.println(Thread.currentThread().getName()+" run about to complete ");
}
}
program ended with following output
main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed
Did i wrongly get the meaning of thread waiting forever or is there something i am missing
note: I know starting thread from constructor is not a recommended practice.. this is exact question in the dumps so i just pasted it (* not pretty much exact actually,i have placed println statements to see flow of the program)
There is no thread that joins itself in your example.
The main() thread in your example creates a new thread and then it joins the new thread.
Don't confuse Thread (i.e., the java object) with thread (the execution of the code.) All of your methods belong to the same Thread object, but they run in two different threads.
James is correct (+1 from me), I'm just trying to make this more explicit. Here is what happens:
Your main thread constructs the startinginconstructor constructor.
The constructor calls start, which will result in the startinginconstructor object having its run method in the new thread.
After that the main thread will proceed to call makeitso. In makeitso this is the startinginconstructor object, so the result is that the main thread waits until the thread represented by the startinginconstructor object has finished.
Java objects can be called by any thread, just because an object extends Thread doesn't mean any invocation of that method is happening on that thread.

How does a thread know that there is a join method ahead

Below is my sample code, when my a.start() called it should create a thread and print "Run" immediately. But why does is called after printing "begin" 20 times.
How does thread "a" decide that it doesn't have to call run() immediately.
public class JoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
for (int i = 0; i < 20; i++) {
System.out.print("Begin");
}
Thread.sleep(1000);
a.join();
System.out.print("\nEnd");
}
public void run() {
System.out.print("\nRun");
}
}
Output:
BeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBegin
Run
End
I am little confused about the behavior of thread.
In my opinion "run" should be printed before "begin" because it get printed before the join() method is called, and at the time of join method called thread "a" must have finished its execution and calling join must be useless at that point.
Calling start() on a thread doesn't necessarily triggers the execution of its run() method immediately. Your thread is marked as started but the main thread pursues its execution into the for loop. Then the JVM is switching to your thread once the main thread reaches the sleep() statement.
You start the thread, then immediately do some printing, then sleep. Looking at your code I would actually expect to see Begin before Run because the thread is being started in the background, concurrently to your main thread going on with its work. Futhermore, the print method is synchronized so you repeatedly acquire that lock in a loop, giving even less chance to the second thread to interject.
I have tried your code with Thread.sleep eliminated, both with and without the join call. The behavior is the same in both cases: Run comes at the end most of the time and occasionally manages to get interleaved between the Begin words. Everything exactly as expected by the simple model of concurrency with synchronized blocks.
Here is a slight variation on your code which reliably prints Run before everything else, whether you call the join method or not. All that changed is the position of the sleep call.
public class JoinTest implements Runnable
{
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
Thread.sleep(1000);
for (int i = 0; i < 20; i++) {
System.out.print("Begin");
}
a.join();
System.out.print("\nEnd");
}
public void run() {
System.out.print("\nRun");
}
}
The start() method calls the thread's run() method, although this takes a little time, which may just be enough for some or all of your 'Begin' loops to complete. When I run this on my machine the 'Run' output appears between the first and second 'Begin'. Try outputting with timestamps so you can see how long your machine is taking to execute each command:
public class JoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
for (int i = 0; i < 20; i++) {
System.out.println("Begin " + System.nanoTime());
}
Thread.sleep(1000);
a.join();
System.out.println("End " + System.nanoTime());
}
public void run() {
System.out.println("Run " + System.nanoTime());
}
}
Calling a.join() at that point ensures that you will always see 'Run' output before 'End', as join() waits for the thread to complete.
I have tried many scenarios with join(), "run" always get printed after "begin" but when i remove the join statement "run" always get printed before "begin". Why?
Because it's allowed. That's why. As soon as you call .start(), you have two threads. Untill your program calls a synchronization methods like .join() it's entirely up to the JVM implementation and the operating system to decide which thread gets to run when.
The a.join() call from your main thread forces the main thread to wait until the a thread has completed its run() method.
Without the a.join() call, the Java Language Specification permits the a thread to complete its work before a.start() returns in the main thread, and it permits the main thread to reach the end of the main() function before the a thread even begins to run, and it permits anything in between to happen.
It's entirely up to the JVM and the OS.
If you want to take control of the order in which things happen, then you have to use synchronized blocks, and synchronization objects and method (e.g., .join()).
But beware! The more you force things to happen in any particular order, the less benefit your program will get from using threads. It's best to design your program so that the threads can function independently of one another most of the time.

Using threads in Java

I have a portion of code dealing with threads and I want to understand its function in detail. The run method is empty in my example, but lets assume it has some operations to do on a global variable:
import java.io.File;
public class DigestThread extends Thread {
private File input;
public DigestThread(File input) {
this.input = input;
}
public void run() {
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
File f = new File(args[i]);
Thread t = new DigestThread(f);
t.start();
}
}
}
After creating a thread and starting it, will it wait to finish the tasks in the run method before creating/running another thread ?
second question
if a variable has declared in run method that means it will be declared many times because every thread created will do the task in run method , is every thread handles its own varible although variable in each thread are same ?
will it waitng for finish the tasks in run method to creat another
method ?
No. That's the whole point of Multithreading. Every thread has it's own stack of execution. So, when you start a thread, it enters the run() method, and executes it in a different stack, and at the same time the main thread continues execution, in it's own stack.
After that, main thread, can spawn another thread. Thus all the threads run simultaneously, but of course, one at a time, sharing the CPU amongst them, based on the specific CPU allocation algorithm being used.
It's not possible to write down all the details about the execution process of multiple threads here. I would rather suggest to read some tutorials or search for some online resources, regarding the concept of Multithreading. Once clear in concept, move ahead with the implementation in Java.
Here's some tutorials links you can start with: -
Thread Wiki Page
SO Multithreading Wiki Page
Concurrency - Oracle Tutorial
http://www.vogella.com/articles/JavaConcurrency/article.html
Once you start a thread, it will run in a separate thread and the main() thread will continue (it may end before the child thread ends).
If you want the thread to finish before main then you can use the Thread.join method on thread to wait for it.
First, Thread is a single sequential flow of control within a program.
We can execute more than one thread in a program, but there is a life cycle, where you can find out how threads work...
Whenever we call the start() method of Thread it automatically calls the overriden method public void run() and executes the code of the run() method...
Here is a simple example of Thread in Java with ABC and XYZ thread classes
/* Write a program to print having two Thread Class 1) ABC with 1 second 2) XYZ 2 second. 10 times with Extend Constructor */
class ABCThreadConstructor extends Thread {
ABCThreadConstructor(String name) {
super(name);
}
public void run() {
try {
for(int i = 0; i < 10; i++) {
System.out.println("ABC");
Thread.sleep(1000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class XYZThreadConstructor extends Thread {
XYZThreadConstructor(String name) {
super(name);
}
public void run() {
try{
for(int i = 0; i < 10; i++) {
System.out.println("XYZ");
Thread.sleep(2000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class AbcXyzThreadConstructorDemo {
public static void main(String args[]) {
ABCThreadConstructor atc = new ABCThreadConstructor("ABCThreadConstructor");
System.out.println("Thread Name : " + atc.getName());
atc.start();
XYZThreadConstructor xtc = new XYZThreadConstructor("XYZThreadConstructor");
System.out.println("Thread Name : " + xtc.getName());
xtc.start();
}
}
Assuming your question is "After creating a thread and starting it, will the program wait for the thread to finish its run method before creating another thread?"
If that's the case, No the program will not wait. t.start() kicks off the thread and it gets its own chunk of memory and thread priority to run. It will do its operations and then exist accordingly. Your main thread will start the number of threads specified in args before terminating.
If you need the application to wait on the thread then use t.join(). That way the parent thread (the one that runs main) will be joined to the child thread and block until its operation is complete. In this case it sort of defeats the purpose of threading but you can store the thread ID for whatever logic you need and join() later.

Compiler logic with Java Multithreading?

So I'm slightly confused as to how multi-threading works. For example, if I create a subclass of Thread called MySub, and this is what it looks like:
public class MySub extends Thread {
public void run {
for(int i = 0; i < 5; i++){
System.out.println(i);
}
}
}
And in the main class I do this:
public static void main(String[] args) {
Thread m = new MySub();
Thread m2 = new MySub();
m.start();
m2.start();
}
Shouldn't it call the start() method for m, and then go straight to calling the start() method for m2, without waiting for the m thread to finish? Isn't that the point of multithreading?
But in actuality, it prints 0 through 4 from the start() call for m, and then 0 through 4 for the start() call for m2. They didn't go concurrently, they went sequentially, which isn't what I expected. I kind of expected a mess of 0 through 4 numbers.
This is a race condition #Jake. Your main is not waiting for the first thread to finish before starting the second. It is starting the first thread which finishes its work before main gets a chance to start the second thread.
If you tried printing (let's say) 1000 numbers or something that takes more time, you would start to see them interleave. Or you could put a Thread.sleep(10) between your println statements which would show it more specifically.
FYI: it is recommended to have your classes implement Runnable as opposed to extends Thread. Then you would do:
Thread m1 = new Thread(new MySub());
m1.start();
Also, use of the ExecutorService code is recommended more than using thread directly.

Categories