Basic Java threading and runnable pattern - java

I have a problem with understanding this code. I have only a couple of hours' knowledge of Java.
Here is the code :
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
And here is output of it :
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Here are my questions.
I want to understand the pattern the code follows. According to me,
First of all, the Program should start to execute the main() function. So, instance of NewThread should be initialized.
Then, I have to go into NewThread constructor and write Child thread: Thread[Demo Thread,5,main]
After that t.start() comes and therefore Program should execute public void run() (AM I WRONG HERE ?? )
In public void run(), I think I should have gotten an output Child Thread 5, but instead I got Main Thread 5. I wonder why ??
Is there anyone to help me ?? Thanks in advance.

t.start() creates a new thread, and calls run() from that. At that point, there are two threads running independently: the one that called start(), and the new one. The original thread returns from the constructor and then starts executing the loop in the main() method.
As the two threads are independent, there's no guarantee which thread will reach a call to System.out.println first. In the sample output that you've given, it so happens that the original thread gets to print first. It could easily happen the other way round though.
As an aside, if you're new to Java I would suggest you learn the basics of the language before you get to threading. There's nothing in your question which indicates that you're confused, but threading is a relatively advanced topic, and it's worth being comfortable with the general language behaviour before you get that far, IMO. That way you can be confident that any odd behaviour you see really is due to threading and not to misunderstanding other parts of the language.

Related

Why Child Threads do not work when using while(true) loop in main thread without sleep?

When using while(true) loop in main thread with Thread.sleep() the child threads works fine but if i remove sleep method from while loop the child threads do not work. I mean, thread defines parallelism so it should work ?
public static void main(String[] args) {
Thread th1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i=0; i<50; i++) {
System.out.println("I love java.");
Thread.sleep(500);
}
}
});
th1.start();
th2.start(); // Similarly assume thread 2
// Here's my main thread
while(true) {
System.out.println("I am main thread.");
// If i use Thread.sleep(200) here, works fine but if not the child thread do not
print messages
}
}
I am new to java, so might be the question is bit silly. Answers will be helpful.
No, it works fine on both situations.
when you use Thread.sleep() in main-thread the main thread executes slower, thus you can see the "I love java" message (because t1 executes first)
when you don't use Thread.sleep() the main thread executes faster, so you can't see the "I love java" message. but it is there (on the first or second line of output)
debug the program to see more information. debugging shows the number of threads running currently and many more information
If you want to learn more about concurrency(multithreading) visit the link
https://www.baeldung.com/java-concurrency

Thread creation by extending Thread class

This is a simple example about creating a thread by extending the Thread class.
class Count extends Thread {
Count() {
super("my extending thread");
System.out.println("my new thread is started " + this);
start();
}
#Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("count " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("my thread run is over");
}
}
}
public class Multi2 {
public static void main(String[] args) {
Count c = new Count();
try {
while (c.isAlive()) {
System.out.println("main thread is alive untill child thread is alive");
Thread.sleep(1500);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("main thread is over");
}
}
}
And my output was this.
my new thread is started Thread[my extending thread,5,main]
main thread is alive untill child thread is alive
count 0
count 1
main thread is alive untill child thread is alive
count 2
main thread is alive untill child thread is alive
count 3
count 4
main thread is alive untill child thread is alive
count 5
main thread is alive untill child thread is alive
count 6
count 7
main thread is alive untill child thread is alive
count 8
main thread is alive untill child thread is alive
count 9
my thread run is over
main thread is over
My questions are,
01. How come main thread is alive untill child thread is aliveoutput printed before count 0
count 1
02.How come main thread is alive untill child thread is aliveoutput keep printing withing the output of run() method?
Please help me to figure this out.
Thank you.
Count has this line:
Thread.sleep(1000);
Your main program has this line:
Thread.sleep(1500);
Clearly, you're going to get 2 main prints for every 3 count prints. That's why 0 and 1 are next to each other.
As for why you see the main print before the count prints, you can see this:
Count c = new Count();
try {
while (c.isAlive()) {
System.out.println("main thread is alive untill child thread is alive");
Thread.sleep(1500);
You've fired off your c but until your JVM performs a context switch to actually run that thread, you might not see results. The truth is you may, on some systems, see your counter before that. Often, because it's so close to when it kicks off and hasn't yielded yet, you'll see the main print before the counter.
For your second part, your main thread is... keeps printing because it has a loop that tells it to print until your counter thread is no longer alive. They both use System.out so when you look at your console you see them both there.

Could someone explain this code, it is related to threading

I am not able to understand how the control is transferring from "Expl Thread" output statement to the "Main Thread" output statement.
package com.myjava.threads;
class MyRunnableThread implements Runnable {
public static int myCount = 0;
public MyRunnableThread() {
}
public void run() {
while (MyRunnableThread.myCount <= 10) {
try {
System.out.println("Expl Thread: " + (++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex) {
System.out.println("Exception in thread: " + iex.getMessage());
}
}
}
}
public class RunMyThread {
public static void main(String a[]) {
System.out.println("Starting Main Thread...");
MyRunnableThread mrt = new MyRunnableThread();
Thread t = new Thread(mrt);
t.start();
while (MyRunnableThread.myCount <= 10) {
try {
System.out.println("Main Thread: " + (++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex) {
System.out.println("Exception in main thread: " + iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}
The output is:
Starting Main Thread...
Main Thread: 1
Expl Thread: 2
Main Thread: 3
Expl Thread: 4
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Expl Thread: 8
Main Thread: 9
Expl Thread: 10
Main Thread: 11
End of Main Thread...
There is no control that is transferred... The threads are independently printing to the console every 100 milliseconds. Since the times are the same, then it appears they "take turns", but which "goes first" is not deterministic.
Change one of the Thread.sleep(100); values and you will see that one will take longer/shorter than the other to print.
how the control is transferring from "Expl Thread" output statement to the "Main Thread" output statement.
Control isn't being passed. Instead each thread is calling
Thread.sleep(100);
And as this is the same amount of time, they take turns. Change one of them to sleep(50) and you will see one prints messages twice as fast.
That is something the thread scheduler decides. When you start the thread, it will run parallel with the other threads that are already there. Its up-to the thread scheduler to decide the order and the time allotted to each thread.
There is no guarantee on the order of execution.

unwanted output in multithreading

class mythread implements Runnable {
Thread t1;
String name = "";
public mythread(String thname) {
name = thname;
t1= new Thread(this, name);
System.out.println(t1);
t1.start();
System.out.println(t1.getName());
}
#Override
public void run() {
for (int i=5;i>0;i--){
try {
System.out.println(Thread.currentThread());
System.out.println("child Thread" + i);
Thread.sleep(2000);
} catch(InterruptedException e){
System.out.println("Child Thread Interrupted");
}
}
}
}
public class Mainthread {
public static void main(String[] args) {
mythread m1 = new mythread("Rohan");
mythread m2 = new mythread("Jain");
try {
for(int i=5;i>0;i--){
System.out.println("Main Thread" + i);
Thread.sleep(2000);
}
} catch(InterruptedException e){
System.out.println("Main Thread Interrupted");
}
}
}
The output is:
Thread[Rohan,5,main]
Rohan
Thread[Jain,5,main]
Thread[Rohan,5,main]
child Thread5
Jain
Main Thread5
Thread[Jain,5,main]
child Thread5
Main Thread4
Thread[Rohan,5,main]
child Thread4
Thread[Jain,5,main]
child Thread4
Main Thread3
Thread[Rohan,5,main]
child Thread3
Thread[Jain,5,main]
child Thread3
Main Thread2
Thread[Jain,5,main]
Thread[Rohan,5,main]
child Thread2
child Thread2
Thread[Rohan,5,main]
child Thread1
Thread[Jain,5,main]
child Thread1
Main Thread1
but the output i want is like first it should print the 5 in thread "rohan" then 5 in thread in "jain" then 5 in thread "main" and so on...please help..!!!!!!
These sort of questions really confuse me. The whole point of threads is that they run asynchronously in parallel so we get better performance. The order that threads run cannot be predicted due to hardware, race-conditions, time-slicing randomness, and other factors. Anyone who is asking about specific order of output in a threaded program should not be using threads at all.
Here are similar answers to the same question:
These three threads don't take turns when using Thread.yield()?
How can I get my threaded program to print specific output
why output comes different everytime instead of synchronized block
Multi threaded Hello World
You may want to use locks on a single object to control the sequencing. Please refer Java Thread Locks tutorial for further details.
Threads are given processor time or scheduled at the OS level. So your program doesn't have direct control over the times when instructions are executed across its own threads. So there is now guarantee of order. There are a handful of OS specific variables that go into scheduling.
If you want to guarantee order across threads than your threads need to communicate that. There are a handful of ways to do this. Most commonly programmers use a mutex; which is also called a lock.

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.

Categories