and this a normal thread program
class Counter implements Runnable {
private int currentValue;
public Counter() { currentValue = 0; }
public int getValue() { return currentValue; }
public void run() { // (1) Thread entry point
try {
while (currentValue < 5) {
System.out.println(Thread.currentThread().getName() + ": " + (currentValue++)); // (2) Print thread name.
Thread.sleep(250); // (3) Current thread sleeps.
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println("Exit from thread: " + Thread.currentThread().getName());
}
}
//_______________________________________________________________________________
public class Client {
public static void main(String[] args) {
Counter counterA = new Counter(); // (4) Create a counter.
Thread worker = new Thread(counterA, "Counter A");// (5) Create a new thread.
System.out.println(worker);
worker.start(); // (6) Start the thread.
try {
int val;
do {
val = counterA.getValue(); // (7) Access the counter value.
System.out.println("Counter value read by " + Thread.currentThread().getName()+ ": " + val); // (8) Print thread name.
Thread.sleep(1000); // (9) Current thread sleeps.
} while (val < 5);
} catch (InterruptedException e) {
System.out.println("The main thread is interrupted.");
}
System.out.println("Exit from main() method.");
}
}
and the output is
Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.
My question is even though the worker thread was started initially before the Main thread enters it's try block, Main thread execution starts first and then when the Main thread goes to sleep child thread gets into action.
As this picture(taken from "A Programmer's Guide To Java SCJP Certification : A Comprehensive Primer 3rd Edition"
Author: Khalid A Mughal, Rolf W Rasmussen) depicts that when the start method is called on the thread it returns immediately.
Please explain this point that why on invoking start method it return immediately and does the thread get starts on calling the start method. As here on calling the start method it doesn't invoke run method of the class. So when does actually the thread starts ?
Also explain this " the call to the start() method is asynchronous."
there are three things that you are missing in your overall analysis.
Call to thread's start method is sequential not parallel. Its the call to run method of Thread that is concurrent. So if you have 5 statements in main method that call start, the 5ht is not going t be called first. Thats the 'happens before' guarantee that JVM specs give you. However the run method of 1 first may get called before or after the call to the second start statement. This depends as its more of a CPU time slicing issue rather than program execution.
When more than 1 thread runs in your program the order of output is in-deterministic. That's because they run in parallel. You can never be sure that the same program will run in same order on two machines or even in two runs on the same machine. In your question you have posted only 1 output. Run the program like 20 times one after another and match the output. I am sure 2 or 3 would be entirely different.
Finally, you are basing your analysis on the order or execution of your concurrent code. That's the biggest blooper programmer make. Concurrent programs are never intended to run in a specific order or sequence. Just try to make your Runnable work an atomic mutually exclusive task (mutually exclusive to the rest of program or even to other Runnables) and track its own execution. Dont mix Threads together.
You cannot directly enforce which Thread is executed/running when. Once you start it, it's handled on lower level(usually by OS) and the results may differ on different machine or even in different execution. If you need more control, you need to use some synchronization mechanism.
The thread is isn't started synchronously underneath the call to start(). It happens later (asynchronously). In other words, just because you called start() doesn't mean the thread has started.
They why and how are all implementation details, that may depend on JVM and/or OS implementations.
Related
public class oneThread extends Thread {
public void run()
{
System.out.println("geeks ");
try {
Thread.sleep(300);
}
catch (InterruptedException ie) {
}
System.out.println("forgeeks ");
}
public static void main(String[] args)
{
oneThread c1 = new oneThread();
oneThread c2 = new oneThread();
c1.start();
c2.start();
System.out.println(c1.isAlive());
System.out.println(c2.isAlive());
}
}
its real output is ->
geeks
true
true
geeks
forgeeks
forgeeks
how is this correct ?
I expected it to be ->
geeks
geeks
true
true
forgeeks
forgeeks
There are lots of legal execution sequences that could give rise to that output.
For example:
in main: c1.start()
in main: c2.start()
in thread 1: println("geeks")
in thread 1: sleep
in main: println(c1.isAlive()); println(c2.isAlive());
in thread 2: println("geeks")
in thread 2: sleep
in thread 1: println("for geeks")
in thread 2: println("for geeks")
JVM terminates since all threads have completed
Other possible execution sequences include:
Steps 3 and 4 could happen before step 2.
Thread 2 could be scheduled before thread 1.
Thread 2 could "overtake" thread 1 due to the sleep times being imprecise.
And so on.
These are all legal behaviors, and on some platforms you might actually encounter them.
This is perfectly valid behavior. The JVM is free to decide which Thread runs and when. Some of the things you should note is that starting a thread takes some time, and while Thread 2 is still starting, main keeps going and gets to its print. Also Threads can be put to sleep for a lengthy IO operation such as System.out.println, and another thread will run while the print is executing.
I'm trying to run four threads. run() method has a for loop that loops 10 times.In each loop the shared resource "x" is increment by 1. When all threads die, the for loop should have run 4x10 =40 times and x value should equal 40.
That is not happening in all runs of the my code.Each time I run the code it prints a different value of x.Most of the output values of x range from 33 to 40.
Why is it not 40 in every run? Does that mean some for loop loops are being skipped? Is it caused due being blocked?
NOTE : this does not happen when sleep() is removed. It prints 40 every single time.
My code :
public class MyThreadImplementsRunnable implements Runnable{
int x =0;
public void run() {
for(int i=0;i<10;i++){
x = x+1;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println("exception");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThreadImplementsRunnable m = new MyThreadImplementsRunnable();
Thread t1 = new Thread(m,"first");
Thread t2= new Thread(m,"second");
Thread t3= new Thread(m,"third");
Thread t4= new Thread(m,"fourth");
t1.start();
t2.start();
t3.start();
t4.start();
//To make sure not to go the next statement unless all threads die
while(t1.isAlive()|| t2.isAlive()|| t3.isAlive()||t4.isAlive()){
}
//After all threads die
System.out.println("now all threads are dead");
//value of the shared resource x after all threads exit
System.out.println(m.x);
}
}
Some test runs gave the following results :
Output:
now all threads are dead
34
Output:
now all threads are dead
33
x = x + 1 loads the value of x from memory, adds 1 to it and then stores it in x. Lets say Thread t1 loads 30 and at the same time thread t2 loads 30 they both increment 30 by 1 and store 31 in x instead of 32.
Why it's always 40 without sleep can be caused by many things I hypothesize that it's caused by each of the threads running very quickly and finishing before the next one starts.
You also don't use volatile and there are visibility issues but for now lets not get into that. This is also something you need to learn if you want to write multi-threaded code.
You are using a shared resource(x) between threads which is bound to create many problems like data race, visibility.. Your answer will be always different
#oleg I don't think Volatile will help in this scenario
I have two threads running: main and child thread. The activities they do are:
Child thread counts the sum of 1 to 100.
Main thread prints the total sum once it's calculated by child (so I used wait and notify). Also it outputs the child thread status.
So below is the code part.
class MainThread {
public static void main(String[] args) throws InterruptedException {
ThreadB b = new ThreadB();
b.setName("Child thread: ");
b.start();
synchronized(b) {
System.out.print("\nwaiting for b to complete\n");
b.wait();
System.out.print("\nno more wait .........................\n");
for (int i = 0; i < 1000; i++)
System.out.print("\n" + b.getName() + "'s state:" + b.getState());
}
Thread.sleep(1000);
System.out.print("\n" + b.getName() + "state:" + b.getState());
System.out.print("\ntotal in " + Thread.currentThread().getName() + "is :" + b.total);
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this) {
for (int i = 0; i < 100; i++)
total += i;
System.out.println(this.getName() + "finished sum, lets notify other objects");
notify();
System.out.println(this.getName() + " done with notify and sync block\n");
}
System.out.println(this.getName() + " : entered non critical section");
for(int j = 0; j < 1000; j++) {
System.out.print("Hi ");
}
}
}
Child finished its synchronized block and notified main thread. and even it's started non synced part which is nothing but printing "Hi " in loop.
Now main thread after notified, resumed its work and prints child's status.
But here is my observation: while executing the "Hi " (for loop which is in non sync block), sometimes child's status is RUNNABLE and most of the times it's BLOCKED. For example:
Child thread: 's state:RUNNABLE Hi Hi Hi
Child thread: 's state:BLOCKED Hi Hi Hi Hi
What caused the child thread to enter in BLOCKED state when executing its non-synced block?
Two threads cannot print to the same device at the same time. If they try, one of them will have to be blocked.
The two threads do not synchronize each other on ThreadB but on the System.out Printstream's write method, which has a synchronized block so only one thread can write to the stream at a time.
public void write(int b) {
try {
synchronized (this) {
ensureOpen();
out.write(b);
if ((b == '\n') && autoFlush)
out.flush();
}
}
I'm not sure I fully understand your question. Are you saying that the child thread hangs? (i.e., are you saying that it becomes BLOCKED forever?) If so, that's probably a lost notification.
Your program contains a data race. After the main thread calls b.start() the two threads race to synchronize on the new ThreadB object. If the ThreadB thread wins the race, it will enter the synchronized block, count up to 100, call this.notify() and then exit.
As soon as the ThreadB thread exits the synchronized block, then the MainThread thread is able to enter its synchronized block, and call b.wait(). The b.wait() call will never return because there's no other thread that will ever call b.notify(): The ThreadB thread is already done and gone by that point.
A call to b.notify() does not do anything at all if there is no other thread that is already waiting. The object, b, does not remember that it was notified.
The wait() and notify() methods are low level primitives that were meant to be used in a very specific way. See the Oracle Guarded Blocks Tutorial for more info.
Sometimes ThreadB runs faster than main thread and gets synchronized (this) first. In this case it should work by your scenario. But sometimes main thread runs in synchronized(b) faster. And then ThreadB gets blocked by main thread that, in turn, waits for notification from b.
Try to remove synchronized block from main thread and relay only on b.wait().
The question was to generate random numbers between 1 and 99 using a thread. However the problem here is I don't know where does the "main thread is stopping" coming from?
Doesn't the main thread die in the end?
This is the sample output:
Main thread stopping
Random no = 57
Random no = 47
Random no = 96
Random no = 25
Random no = 74
Random no = 15
Random no = 46
Random no = 90
Random no = 52
Random no = 97
Thread that generates random nos is stopping
Mythread class:
public class MyThread extends Thread {
MyThread() {
// default constructor
}
MyThread(String threadName) {
super(threadName); // Initialize thread.
start();
}
public void run() {
// System.out.println(Thread.currentThread().getName());
Random rand = new Random();
int newValue;
for (int i = 0; i < 10; i++) {
newValue = rand.nextInt(99);// generates any vale between 1 to 99
System.out.println("Random no = " + newValue);
}
System.out.println("Thread that generates random nos is stopping");
}
}
Main class:
public class HW5ex2a {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join();// wait for the thread t to die
System.out.println("Main thread stopping");
}
}
You can't rely on the order that main thread and other threads write to System.out.
Your thread t executes fine, the main thread waits for it to finish and then the main thread exits, all as expected. But this isn't reflected in the order that you see on System.out.
To directly answer your question - the main thread waits for the thread to finish, then it writes a message to System.out, then it dies. The only confusing thing is that, because you are writing to System.out from two different threads, you don't have any guarantees about the relative ordering. Println's from the two different threads could show up interleaved in any way...it just happens to show up with the output from the main thread first.
As Alexis Leclerc points out - you get an unpredictable interleaving, the same as in this java threads tutorial.
Memory Synchronization in a Multi-core System
Since both threads are being run on separate cores (most probably), the objects that the threads have access to are cached by each core (in L1 cache) for improved performance.
Whenever the state of the object is changed, all caches try to synchronize with value in RAM, which is not guarantied to occur immediately.
Some threads might be able to synchronize before other threads even if it violates happens-before relationship between them.
The reason behind this lies in the implementation of the java memory model.
The same thing is happening with System.out object here.
You can not guaranty the order in which the data is passed and flushed through it.
Therefore it is unpredictable. Calling
System.out.flush();
might improve the result, but it will not guaranty.
For more, refer to Multiple threads using System.out.println in Java
Hope this helps.
The main thread exit on below situation :-
Normally when program execution complete .
If you are using System.exit(1).
JVM crashes.
Hope it will help you.
I am reading Java Thread Programming a book by Paul Hyde.I am into intial chapter. I am running various sample programs in Eclipse IDE.
public class TwoThreadAlive extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
// get a reference to the thread running this
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args) {
TwoThreadAlive tt = new TwoThreadAlive();
tt.setName("my worker thread");
System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),tt.isAlive()=" + tt.isAlive());
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
System.out
.println("at the end of main(), tt.isAlive()=" + tt.isAlive());
}}
This program is giving SAME output every time I run it.But it has mentioned that output will differ as JVM will be busy in context switching.Can you please tell me that why it is giving same output?
And it is giving
at the end of main(), tt.isAlive()=true
This should have been
at the end of main(), tt.isAlive()=false
Please help me , this is making me mad.
Nope, the output is correct because by the time the main method executes the last println there is no guarantee that also your thread has finished executing. Add a tt.join(); right before the last print:
tt.join();
System.out
.println("at the end of main(), tt.isAlive()=" + tt.isAlive());
Now the main thread will be blocked until tt finishes, and so the println will execute only after tt is dead.
As for your output being always the same, 10 is a too fine grain value and most likely each thread finishes printing everything by the time it gets context switched. Try with a much larger value.
Not really clean readable code, I think the printMsg() should be static and maybe be placed inside the main class. That way you'll be able to notice that its behavior is not dependent on the custom thread class. Since it prints the current thread name, you could see (for a higher number of iterations) the JVM switching between your TwoThreadAlive thread and the main thread.
About the isAlive question, the TwoThreadAlive thread may not have finished its execution when the main finishes. Change the main thread iterations to 100 and the custom thread to 10000 to see this effect.