Reputation: 165
I am actually very beginner in java field and currently going through multithreading concepts
I came across a program and had certain doubts regarding the program itself.
Following is my program
public class SecondThreadDemo implements Runnable {
public void run() {
System.out.print(Thread.currentThread().getName());
}
}
class B implements Runnable {
public void run() {
new SecondThreadDemo().run();
new SecondThreadDemo().run();
new Thread(new SecondThreadDemo(), "T3").run();
new Thread(new SecondThreadDemo(), "T2").start();
new SecondThreadDemo().run();
new Thread(new SecondThreadDemo(), "T3").start();
}
}
class C {
public static void main(String[] args) {
new Thread(new B(), "T1").start();
}
}..
Now what I was expecting is the following output
T1T1T1T1T3T3
but its coming like
T1T1T1T1T2T3
Can someone clarify the output?
Upvotes: 0
Views: 130
Reputation: 11
new SecondThreadDemo().run();
- Simple Function call so T1 as running thread is T1
new SecondThreadDemo().run();
- Simple Function call so T1 as running thread is T1
new Thread(new SecondThreadDemo(), "T3").run();
- Simple Function call so T1 as running thread is T1
new Thread(new SecondThreadDemo(), "T2").start();
- At this point you are creating a thread with name T2 and calling start, here it depends it can print T2 or may be next line will get executed and will print T1 before this thread prints T2
new SecondThreadDemo().run();
- T1 simple function call
new Thread(new SecondThreadDemo(), "T3").start();
- T3 as expected
so it wil depend on JVM output can be T1T1T1T1T2T3 or may be T1T1T1T2T1T3
Upvotes: 0
Reputation: 7836
A new thread in java will spawn only if you call start method on thread, which will execute the code written in the run method in a new thread.
But if you directly call run() method on thread or runnable object then it will be executed in the main thread of execution not in a new thread.
Upvotes: 0
Reputation: 347184
There's a difference between run
and start
.
Runnable
itself isn't a Thread
so it will execute inline with the rest of your code (like calling any other method).
start
schedules a thread which will can run
of your Runnable
, in your example.
There will also be differences each time you run it and it will come down to how the thread scheduling is working
For example, you code does this...
new SecondThreadDemo().run();
new SecondThreadDemo().run();
new Thread(new SecondThreadDemo(), "T3").run();
new Thread(new SecondThreadDemo(), "T2").start();
new SecondThreadDemo().run();
new Thread(new SecondThreadDemo(), "T3").start();
This would (possibly) output something like...
T1 (run)
T1 (run)
T1 (run) (cause I'm in T1's thread context)
// Then it all depends...this MIGHT be the output...
{T1} (run)
{T2} (start)
{T3} (start)
Upvotes: 10