mulithreading in java example - java

Here is a sample program in java from tutorials point:
// 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.");
}
}
The output of the program is as follows.
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.
I have trouble understanding why the main thread is executing before the child thread. In the program you can see that first new NewThread() is executed. The NewThread class instantiates a new thread and calls the start() function on the new thread which then calls the run() function.
The loop in the main function comes only after a new thread is created. However when the program is run , The loop in the main thread is run before the child thread. Please help me understand.

The loop in the main thread is run before the child thread. Please help me understand.
Threads do not have any form of synchronization by default and can run in any order with their executions possibly interleaving. You can acquire locks and use those for ensuring order, for example if the main thread acquires the lock before starting the child thread, having the child thread wait to acquire the lock, and having the main thread release the lock once it's done with its tasks.

Thread.start() schedules the thread to be run. After that it's up to the JVM (and the OS) to look after the scheduling. How the threads run is determined by a number of factors including the number of CPUs/cores you have, the OS, the priority etc.
If you need the threads to run in a particular order, wait for each other etc., then you have to use the threading tools provided (synchronisation, locks etc.) Otherwise it's completely arbitrary.

Related

why does the main thread wait

In the below code, why does the main thread wait until the child thread is finished.
Driver.java
public class Driver {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ThreadRunner());
t.start();
}
}
ThreadRunner.java
public class ThreadRunner implements Runnable {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Child thread" + i);
}
}
}
Here in the Driver class after calling 't.start()' shouldn't the program quit? I'm not using join but still the main thread waits until the newly spun 'ThreadRunner' run is running. Is it because in java the main thread (which is started by main method) always waits until all the threads are shut?
The main thread exits immediately after having started the other thread, but the Java program as a whole continues running as long as there are non-daemon threads alive (and unless you specifically request it, new threads will be non-daemon).
Making the thread a daemon thread is easy: simply call t.setDaemon(true); before starting it.
The main thread doesn't actually wait. The main thread completes. The program does not quit because you create a Thread that is non-daemon. The JVM will shut down when only daemon threads remain.
you can add 'System.out.println("main thread");' below 't.start()'
then you can see main thread is the first.

Why is that sleeping inside a thread causes problems with `notify`?

Driver.java
public class Driver {
static Object obj = new Object();
public static void main(String [] args) throws InterruptedException
{
Thread thr = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Thread 1: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 1: Completed processing.");
System.out.println("Thread 1: Notifying other waiting threads.");
obj.notify();
}
}
});
Thread thr2 = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Thread 2: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 2: Completed processing.");
System.out.println("Thread 2: Notifying other waiting threads.");
obj.notify();
}
}
});
thr.start();
thr2.start();
System.out.println("Main Thread: All processing units busy.");
// Thread.sleep(2000); // Enable this and disable the other Thread.sleep(...) and NOW we are good. But again, 'why?' is the question.
synchronized(obj){
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
System.out.println("Main Thread: Found ONLY 1 available slot.");
obj.notify();
obj.wait(); // JVM should catch this as the last request so it has the least priority.
System.out.println("Main Thread: Finished and exiting...");
}
}
}
The code above will not notify the Threads because of the following line:
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
Please take a look at this line in context with the whole class. I am having hard time pinpointing to the reason why this simple proof-of-concept would fail if that line is placed inside ther synchronized block in the Main Thread.
Thank you
The problem is not the sleep but rather that the main thread almost always acquires the lock before one (and occasionally both) of the created threads does. If you print just inside the synchronized blocks it's much more clear what is going on:
synchronized(obj) {
System.out.println("this thread acquired the lock");
You'll see the output is almost always Thread #1, then the main thread, and finally Thread #2 after Thread #1 completes (but main has already returned).
If you run it enough times sometimes both child threads do acquire the lock first and it completes.
The reason moving the sleep to outside the synchronized block in the main thread works is it allows both child threads to reach their respective wait statements.
Read the doc.
Wakes up a single thread that is waiting on this object's
monitor.
If it is sleeping then it is not waiting.
There is other related problem, it is not possible to reach the notify line while the other thread is in the sleep as it keeps the monitor (lock) and the other thread can't run inside the synchronized block. This is always that way as both wait and notify must be run inside related syncrhonized blocks (against the same monitor).
sleep holds the lock, but wait doesn't. so when your main thread is sleeping, both thr and thr2 can't get the lock until main thread notifies them. At that moment, they start to wait and can't receive any notify()
The problem is that sleep does not release the monitor, that is: while the main thread is sleeping, all the other threads cannot enter the synchronized block, so they are basically sleeping with the main thread.
The moment the main thread wakes up, it does notify, but since no one yet entered the wait() position, no one is listening. Then the main thread waits and therefore releases the monitor, so now all threads can proceed to the wait() state, but no one is left to wake them up. -> Deadlock

Run multiple thread at a same time then run main thread

I have to run multiple threads ||ly and after execution of all these thread main thread continue.
For eg I have one main thread and 3 sub threads, my need is
run main thread
pause main thread
run all 3 sub threads ||ly
after complition resume main thread
I create a class extends Thread and call start method of all these thread but it doesn't solve my problem.
My Code:
for (MyThread myThread : myThreads) {
myThread.start();
}
Thanks for help.
Try using Thread.join();
public class ThreadDemo implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits for this thread to die
t.join();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
}
Output:
Thread-0, status = true
Thread-0, status = false
Here is a stack-over-flow link for reference.
Forget 'pausing' threads. Your schedule should be
Initiate X actions on X threads
Wait for all threads to finish
Process results (if any)
So how do you wait for threads to finish? You need a synchronization mechanism. These are often OS level 'flags' called semaphores but the java library gives you a few ways of doing it. You will get a lot out of this series, particularly part 2: Thread Synchronization
CountDownLatch is much more flexible mechanism then Thread.join. It does exactly what you want. Prefer java.util.concurrent.* instead of old builtin java techniques.
Advantages:
Using CDL you deal with a single object instead of bunch of thread. That could simplify code.
It has a getCount() method which could be used to implement progress bar. With joins its much more complicated.
await(long timeout, TimeUnit unit) could be considered more comfortable than join(long millis)
You can call join() on the threads. Assuming that your threads are in myThreads and you don't want your thread to be interruptible
// ...
// create threads and start them
// ...
for (Thread t : myThreads) {
while (t.isAlive()) {
try {
t.join();
} catch (InterruptedException e) { }
}
}
If it should be interruptible:
// ...
// create threads and start them
// ...
for (Thread t : myThreads)
t.join();

Java, Threads, will only run() block be part of the thread or also the code after a start() call?

I'm starting Threads in java, I would like to have a clear idea of how start()/run() acts in my situation.
I've created a thread calle t, and I've placed t.start() followed by a for cycle.
Will the for cycle be part of the thread.t or is it part of the main thread??
class Job implements Runnable{
Thread t;
Job(String tName){
t=new Thread(this, tName);
System.out.println("This is thread: "+t.getName());
t.start();
System.out.println("This is the end of constructor");
try{ /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
for(int i=0;i<5;i++){
System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}
}
public void run(){
System.out.println("This is the start of RUN()");
try{
for(int i=0;i<5;i++){
System.out.println("This is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}
finally{
System.out.println("Fnally block reached: "+t.getName());
}
}
}
I would like to have a clear idea of how start()/run() acts in my situation
start() method spawns a new thread of execution and executes the run method in that thread. In this case , the thread will have its own call stack. Whereas, calling run() method directly doesn't spawns a new thread. Instead this will cause the run() method to execute in the current executing thread having old call stack.
Will the for cycle be part of the thread.t or is it part of the main thread??
The for cycle will be part of the Thread(in your case is main thread if you create Job instance in main thread) from which Thread t is spawned. And if you want to confirm then simply print the name of thread which is executing that for loop using Thread.currentThread().getName() . Example:
try{ /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
System.out.println(Thread.currentThread().getName()+" is executing this for loop");
for(int i=0;i<5;i++){
System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
The method t.start() and the following try/for code are executed in the same thread. This is the main thread if you called the Job(String) constructor from the main thread.
The run() method is executed in the new thread.
Will the for cycle be part of the thread.t or is it part of the main thread??
The main thread. When a thread is forked, the new Thread just calls the run() method. In your case, the main thread calls start() and then continues to run the for() method. This actually will most likely be called before the new thread is finished starting. The new thread that is forked only calls the run() method and any other methods used by run().
FYI, it is considered very bad practice to start a thread from within an object constructor. This "leaks" references to the current object while it is still being initialized. You should consider adding a start() method onto the Job or call start() after the Job constructor has finished.
Job job = new Job(...);
job.start();
Also, since the main thread is the one running your for loop, it will throw InterruptedException only if the main thread gets interrupted -- not the Job thread.
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}

Confusion on Thread setDeaemon in java

According to java when setDaemon is set to true
it does not prevent the JVM from
exiting when the program finishes but
the thread is still running. An
example for a daemon thread is the
garbage collection.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true, actually it should keep on running . when setDaemon is set false the child thread print value of i even though main thread exited.
kindly clarify my doubt.
public class DeamonSample implements Runnable
{
public void run()
{
try
{
System.out.println("T1 started...");
for (int i=0;i<1000;i++)
{
TimeUnit.SECONDS.sleep(1);
System.out.print(i+" ");
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
System.out.println("T1 ended...");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Main Started...");
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
DeamonSample deamonSample=new DeamonSample();
Thread t1=new Thread(deamonSample);
t1.setDaemon(true);
t1.start();
System.out.println("T1 Type="+t1.isDaemon());
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
System.out.println("Main ended...");
}
}
By default threads are not daemon threads. If you get to the end of your main with any thread that's not a daemon then the process will keep running. By calling setDaemon(true) you're telling the JVM that your thread shouldn't block shutdown at the end of main.
The DeamonSample instance is assuredly not stopped when t1.setDaemon(true); is executed; the nondeterminism that you see comes from the prints. Characters are written to thread-local buffers before they are merged into a single stream.
Here's a bit of code to illustrate. Two threads take turns incrementing a counter and printing its state, but the numbers you see may be very much out of order.
import java.util.concurrent.atomic.AtomicInteger;
public class FunnyPrinter extends Thread {
static AtomicInteger counter = new AtomicInteger(0);
int parity;
public FunnyPrinter(int parity) {
super();
this.parity = parity;
}
public void run() {
for (;;)
if (counter.intValue() % 2 == parity)
System.out.println(counter.incrementAndGet());
}
public static void main(String[] args) {
FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
t1.start(); t2.start();
}
}
If you need determinism, synchronize on System.out and flush it before the end of the block.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true
This will not happen. Check your output again. Your output will contain the following lines:
Main Started...
Main Thread Type=false
T1 Type=true
Main Thread Type=false
Main ended...
..actually it should keep on running .
Being a daemon thread, it wont. Since all non-daemon threads (main) have finished, the jvm will exit.
when setDaemon is set false the child thread print value of i even though main thread exited. kindly clarify my doubt.
Correct
The main-thread terminates, before your daemon-thread can print out all your numbers...
if your new thread isDaemon = true, try this line after starting the thread ():
...
Thread t1=new Thread(deamonSample);
try{
t1.join();
}catch(InterruptedException ie){
ie.printStackTrace();
}
...
you will see, the daemon-thread will come to an end... (at least, that wouldn´t be multithreading anymore, but that example is for clarifying purpose only)

Categories