youre an excellent teacher. After watching some 10 videos I know for sure Ill learn java.Earlier I used to hate programming coz I didnt understand properly.Thankyou for increasing my Interest sir. Great teaching . :-)
No, it's not, we have to use synchronization only when we want that only one thread should execute at a time. So in synchronization one thread will execute at a time but which thread will execute we cant give a guaranty. Now in the Producer consume problem it is mandatory that our producer thread must complete its execution before the consumer, but by simply using synchronized keyword we cant achieve that, that's why we need to use wait(), notify(), and notifyAll() here.
if wait is called on some thread and notify is not called then thread might become runnable again after some time , so its better to use while loop and call wait inside that so that even if thread wakes up it can check the condition and go to sleep again if the condition is not met. Here i belive u can use if because notify is called and time lapse is not that much.
Navin Sir, thank you so much. You know, juggling up with so many threads threads in my JavaFx pong game. I wish I had someone like a mentor to me in Java. Your videos are there but I don't know how can I connect you if I get in to some problem which I can't find over google. Still, thank you so much for your videos. Half of Java and Python, I have learned from you. Waiting if you have some forum where I can connect you.
All this can be done without the use of wait() and notify() and synchronized(). why do we have to use all this? Also you were not able to properly explain how notify works and why synchronized is used. Poor explanation!
Wait releases the object lock and notify keyword enters the thread in entry set so that it can acquire object lock after the lock is released by the thread
what if we have 3 threads t1,t2 and t3. t1 and t2 are waiting and when t3 complete its task we need to notify thread t1.. not thread t2... how it will be done...??
Only one of the thread will be able to get into the synchronized method when you call notifyAll(). Which one ? Whichever has the highest priority. If all have same priority then you can't say exactly which one will get into its method.
no, Synchronized method is to avoid other thread to call same method suppose if t1 and t2 are producer threads , lets say t1 calls put method and went to wait state but in the mean time t2 thread comes into picture and calls the put method again so in that case producer method produce new value even consumer thread say t3 not consume earlier value ,so the conclusion is to avoid different threads t1 and t2 call same method we use method synchronization
can someone briefly explain the logic line by line from the start because i am a bit confused with the program when it reaches the while statements i class Q
We could achieve this same logic even without using wait() and notify() by using this valueSet check, they why should we go for wait() and notify() here.? Am I got anything wrong.??
it notify() only one thread which is waiting for resource to release a lock in this case sync function aquires lock while wait() releases lock on resource which is Q and waits itself for other to use it the other thread gets notified that there is release in resource you can use it first it aquires lock on resource then then same waits itself the sir is really confused here and he is mugging up concept of sync i think maybe i am wrong but from video he looks bit confused because there is also no need of other boolean variable if you can change the logic
for ur clarification see this code public class ProducerConsumer { public static void main(String[] args) throws Exception { Q lock = new Q(); Producer p = new Producer(lock); Consumer c = new Consumer(lock); p.start(); c.start(); } } class Q { int i=0; void setI(int num){ this.i=num; } int getI(){ return this.i; } } class Producer extends Thread { Q lock; Producer(Q lock) { this.lock = lock; } @Override public void run() { try { synchronized (lock) { while (true) { lock.setI(lock.getI() + 1); System.out.println("Producer produced -> " + lock.getI()); Thread.sleep(2000); lock.notify(); lock.wait(); } } } catch (Exception e) { } } } class Consumer extends Thread { Q lock; Consumer(Q lock) { this.lock = lock; } @Override public void run() { try {
synchronized (lock) { while (true) { System.out.println("Consumer consumed -> " + lock.getI()); Thread.sleep(1000); lock.notify(); lock.wait(); } } } catch (Exception e) { } } } the main important thing here is not to control the function but acquiring and releasing lock on resources i was interviewed by oracle and somewhat felt humiliated by not understanding concept in depth for mutlithreading
shanmukhi shammu You have basically made Q threadsafe by synchronising both put and get. This synchronisation is governed by intrinsic this lock so at a time only one of the threads can execute either of the two methods. I hope this clears.
The wait and notify logic should come inside the producer and consumer thread instead of Q class. is not it? Those logic shuold not be controlled externally.
I think that this is wrong, the synchronization is happening because of synchronize key word not because wait/notify - one thread doesn't have reference to the other. high risk of dealock.
not sure why, the code doesn't works at my end. this particular line gives error "Thread t = new Thread(this, "Producer"); " If I remove "this" keyword the error gets solves in eclipse but code does not RUN, after that error message is: Error: Could not find or load main class InterThread '' I tried to fix the problem referring to the book called JAVA.the.complete.reference but couldn't solved. Please check if anyone can help .
Do u think wait method can b called out of synchronized block....? Pls refer this "The wait(), notify(), and notifyAll() methods should be called for an object only when the current thread has already locked the object's lock. This point sometimes goes unnoticed because programmers are used to calling these methods from within synchronizedmethods or blocks. Otherwise, you will get "java.lang.IllegalMonitorStateException: current thread not owner" at runtime"
sir can you please make tutorial videos forconcurreny in java.(like using atomic variabes, use a reentrant ReadWriteLock, use java.util.concurrent collections, synchronizer classes, ExecutorService to concurrently execute tasks, apply fork-join framework)
Yes brother. Here as you can see in Producer and Consumer classes we have just created References of Class Q and then we have assigned the location of object passed to them. We are not creating new objects in Consumer and Producer classes instead we are using the object that was passed. Just references we have created. U can say pointers (just to expain i am using c or c++ term).
Very wrong solution. There is no even inter-thread communication here except that horrible while loop. Go learn the true consumer/ producer pattern in multithreading using wait/notify or simply a blocking queue.
sir is it necessary to wait in get method if flag is already true // class Count { int count; boolean flag = false ; public synchronized void put(int count) { if(flag) { try { wait();}catch (Exception e) { } } System.out.println("put : "+count); this.count=count; flag=true; notify(); } public synchronized void get() { /*if(!flag) { try { wait();}catch (Exception e) { } }*/ System.out.println("get : "+count); flag=false; notify(); } }
to synchronize calculations.. if you are calculating a big set of data and some parts can be done independently while some needs to be all finished before the next step can take place.. this is when one thread needs to know what the other thread is doing.. when you iterate on the same data..
start with easy ones brother by urself.I mean u can try simple thread creation and sleep calls in a simple code then try to figure out whats how this is getting callled and whats happening on method call.
Worst Explanation. Many things are wrong in this example. Refer Java concurrency in practice. Merely getting the right output is not enough in multithreaded programming.
Didn’t like this video. More I try to understand using this video, more confused I get. Please try to explain the use case first and also do you homework before creating the video so that you don’t have to do so many hit and try in the video.👎
There are so many tutorials on Multi Threading but I found your explanation as the best one.
Can't explain simpler than this. All videos on thread are great.
hi can u expalin the working logic of while statements in class q class.
thank u
youre an excellent teacher. After watching some 10 videos I know for sure Ill learn java.Earlier I used to hate programming coz I didnt understand properly.Thankyou for increasing my Interest sir. Great teaching . :-)
Subscribed and will surely donate once i get my first salary. This guy deserves it for his work.
seedhi baat no bakwaas! Great Explaination.
One of best vedio on producer and consumer on UA-cam !!!
Thank u sir💞💞💞🌹🇮🇳🇮🇳🇮🇳🇮🇳
Only we have to use synchronised method Instead of doing other hard stuff ... Try
Nice bro
No, it's not, we have to use synchronization only when we want that only one thread should execute at a time. So in synchronization one thread will execute at a time but which thread will execute we cant give a guaranty. Now in the Producer consume problem it is mandatory that our producer thread must complete its execution before the consumer, but by simply using synchronized keyword we cant achieve that, that's why we need to use wait(), notify(), and notifyAll() here.
No
very great explanation.. but i have a doubt why do you use while(setValue) instead we can use if(setvalue) ??? rply
if wait is called on some thread and notify is not called then thread might become runnable again after some time , so its better to use while loop and call wait inside that so that even if thread wakes up it can check the condition and go to sleep again if the condition is not met. Here i belive u can use if because notify is called and time lapse is not that much.
All videos on multithreading was great and understandable but this one is very confused I slept watching this video woke up now
It was great!
Some people want to get everything ready, so why are you programmer?!
It was really helpful thx!
Navin Sir, thank you so much. You know, juggling up with so many threads threads in my JavaFx pong game. I wish I had someone like a mentor to me in Java. Your videos are there but I don't know how can I connect you if I get in to some problem which I can't find over google. Still, thank you so much for your videos. Half of Java and Python, I have learned from you.
Waiting if you have some forum where I can connect you.
Try connecting on Linkdin or his website
Multithreading beyond theory waw telusko
Hi , Didn't understand the usage of notify function . i tried to run the program without the notify() function and it runs properly .
Little bit confusing but still manageable. Other videos are great
All this can be done without the use of wait() and notify() and synchronized(). why do we have to use all this? Also you were not able to properly explain how notify works and why synchronized is used. Poor explanation!
Cause he is explaining without blockingQueue..
Sweety, ever heard of constructive criticism?
Actually synchronized key word gets the object lock. Research it and it would be clear
Wait releases the object lock and notify keyword enters the thread in entry set so that it can acquire object lock after the lock is released by the thread
@@Saifullah-su8ti thanks man
if you guys know all of these, then what the hell youre doing here?
what if we have 3 threads t1,t2 and t3. t1 and t2 are waiting and when t3 complete its task we need to notify thread t1.. not thread t2... how it will be done...??
reply if you find answer for this
use notifyAll( );
Aarush Verma notifyall() will let all thread in process. but I want to notify just 1 thread , not all??
Only one of the thread will be able to get into the synchronized method when you call notifyAll(). Which one ? Whichever has the highest priority. If all have same priority then you can't say exactly which one will get into its method.
NotifyAll() will solve this problem. It has same functionality as notify but it will notify all other threads instead of only one
Can you implement dining philosopher problem using threads.
thanks for clear explanation
But, it does the same job just with the 2 synchronized put() and get() methods, without the need of wait() and notify()..I did not get the point.
no, Synchronized method is to avoid other thread to call same method suppose if t1 and t2 are producer threads , lets say t1 calls put method and went to wait state but in the mean time t2 thread comes into picture and calls the put method again so in that case producer method produce new value even consumer thread say t3 not consume earlier value ,so the conclusion is to avoid different threads t1 and t2 call same method we use method synchronization
did you get the answe ?? cz my comment is same:(
Please add some videos on Thread pools, deadlock and daemon lock..
Can we get a video about thread pool?
u can check video of Defog Tech. Its a pretty good channel consisting videos of multithreading high concepts
can someone briefly explain the logic line by line from the start because i am a bit confused with the program when it reaches the while statements i class Q
excellent sir...well explained
We could achieve this same logic even without using wait() and notify() by using this valueSet check, they why should we go for wait() and notify() here.?
Am I got anything wrong.??
Very good example for learning this concept. Thank you Navin !!
Thanks for good session
you seem to be confused.
What is the best way to study RX Java? Any sugestions
Sir, u have explained it very nicely.
Beautifully explained.Thank You.
hi can u explain the working logic of while statements in class q class. thank u
Really good job.. thnx fr the videos..
It does not work as expected. Even when i don't have notify(), the program is running. And get is before put.
what java version you're running?
Incase of multiple producers and consumers , how does notify() method exactly work ?
Does it notify all threads ?
it notify() only one thread which is waiting for resource to release a lock in this case sync function aquires lock while wait() releases lock on resource which is Q and waits itself for other to use it the other thread gets notified that there is release in resource you can use it first it aquires lock on resource then then same waits itself the sir is really confused here and he is mugging up concept of sync i think maybe i am wrong but from video he looks bit confused because there is also no need of other boolean variable if you can change the logic
for ur clarification see this code
public class ProducerConsumer {
public static void main(String[] args) throws Exception {
Q lock = new Q();
Producer p = new Producer(lock);
Consumer c = new Consumer(lock);
p.start();
c.start();
}
}
class Q {
int i=0;
void setI(int num){
this.i=num;
}
int getI(){
return this.i;
}
}
class Producer extends Thread {
Q lock;
Producer(Q lock) {
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
while (true) {
lock.setI(lock.getI() + 1);
System.out.println("Producer produced -> " + lock.getI());
Thread.sleep(2000);
lock.notify();
lock.wait();
}
}
} catch (Exception e) {
}
}
}
class Consumer extends Thread {
Q lock;
Consumer(Q lock) {
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
while (true) {
System.out.println("Consumer consumed -> " + lock.getI());
Thread.sleep(1000);
lock.notify();
lock.wait();
}
}
} catch (Exception e) {
}
}
}
the main important thing here is not to control the function but acquiring and releasing lock on resources i was interviewed by oracle and somewhat felt humiliated by not understanding concept in depth for mutlithreading
All other explanations are good but this i really din’t understand
Thank you so much
It cleared everything
sir can we do that like adding sleep(10) in between new Producer and new Consumer for this output
yes u can use. It will work i=even if u dont call sleep. Here wait and notify are main concepts.
even without wait and notify methods ,i am getting the same expected output with just synchronized get and put methods
can u please explain why??
shanmukhi shammu You have basically made Q threadsafe by synchronising both put and get. This synchronisation is governed by intrinsic this lock so at a time only one of the threads can execute either of the two methods. I hope this clears.
In Consume class, increase the sleep time then you will understand and test without calling wait and notify methods
Is the source uploaded somewhere?
100/100 marks sir bahut accha
thankyou very much!! now i solved my problem
The wait and notify logic should come inside the producer and consumer thread instead of Q class. is not it? Those logic shuold not be controlled externally.
I think that this is wrong, the synchronization is happening because of synchronize key word not because wait/notify - one thread doesn't have reference to the other. high risk of dealock.
always make concept very difficult i dont like big big example for small concept.
Very good explanation. Thank you.
Sir, I have a question that if we call the sleep() method then the thread will go to waiting state?
The thread will not go into a waiting state, the sleep method stops the current thread execution for a specific time.
@@HimanshuSingh2009 thanks 👍
not sure why, the code doesn't works at my end. this particular line gives error "Thread t = new Thread(this, "Producer"); " If I remove "this" keyword the error gets solves in eclipse but code does not RUN, after that error message is: Error: Could not find or load main class InterThread
''
I tried to fix the problem referring to the book called JAVA.the.complete.reference but couldn't solved.
Please check if anyone can help
.
this keyword cannot be used within static method. Make sure it is not static to use this.
how producers notify() notifies consumers thread? how are they're connected to each other?
notify() simply wakes up one of the threads waiting on the same lock, and notifyAll() method wakes up all the threads waiting on the same lock.
This concept works without wait and notify. Also one more point here is that we need to use synchronized for notify method, not wait method.
Do u think wait method can b called out of synchronized block....? Pls refer this "The wait(), notify(), and notifyAll() methods should be called for an object only when the current thread has already locked the object's lock. This point sometimes goes unnoticed because programmers are used to calling these methods from within synchronizedmethods or blocks. Otherwise, you will get "java.lang.IllegalMonitorStateException: current thread not owner" at runtime"
well explained short and crisp
this passed in Thread() is not runnable obect it is from class Q ,so how it is able to use run ()
Why is valueSet inside while and not inside if?
That's why he used try catch
sir can you please make tutorial videos forconcurreny in java.(like using atomic variabes, use a reentrant ReadWriteLock, use java.util.concurrent collections, synchronizer classes, ExecutorService to concurrently execute tasks, apply fork-join framework)
I had a doubt, are we using the concept of shallow copying here ?
Yes brother. Here as you can see in Producer and Consumer classes we have just created References of Class Q and then we have assigned the location of object passed to them. We are not creating new objects in Consumer and Producer classes instead we are using the object that was passed. Just references we have created. U can say pointers (just to expain i am using c or c++ term).
All videos of Multi threading are good except this one. Please explain step by step. Cant understand why waiting is going on.
Sir can you please make a video on thread pool and thread group.
Hi Navin, I find that if we don't use the notify() method and 'synchronized', it also works fine. Is it the right way to do it like that?
There maybe a case in which both threads will wait on each other and may lead to deadlock , it's better to use wait and notify as a pair.
this is a very complex code for beginner.
Why while loop not run infinite....the condition is always true?
he stopped program Running
Control c ..... u can stop
AWESOME♥♥
very useful
It gives me an error saying class producer nd consumer is already defined
Sir, why you have made the put( ) and get( ) function synchronized
We are using wait method so , it is mandatory to keep the method as synchronized
Sir, while creating the Thread object in Producer class, is this keyword used to call Q's class object ??
yes.
Why u have used while(valueSet), why not if(valueSet)
Google "Java Spurious wake up".
How to count number of producer and consumer
Very wrong solution. There is no even inter-thread communication here except that horrible while loop. Go learn the true consumer/ producer pattern in multithreading using wait/notify or simply a blocking queue.
this course Is great, thank you so much. awesome!
i din't understand Q q; how its possible please someone explain ..
sir is it necessary to wait in get method if flag is already true
//
class Count
{
int count;
boolean flag = false ;
public synchronized void put(int count)
{
if(flag)
{
try { wait();}catch (Exception e) {
}
}
System.out.println("put : "+count);
this.count=count;
flag=true;
notify();
}
public synchronized void get()
{
/*if(!flag)
{
try { wait();}catch (Exception e) {
}
}*/
System.out.println("get : "+count);
flag=false;
notify();
}
}
Thread t = new Thread (this)
Kya koi bata sakta he this keyword kyon use kiya gya he please
you have to implement "synchronized "
why inter-thread communication?
to synchronize calculations.. if you are calculating a big set of data and some parts can be done independently while some needs to be all finished before the next step can take place.. this is when one thread needs to know what the other thread is doing.. when you iterate on the same data..
How many Ads you are subscribed to buddy 🤔
Wondering, are we marketing in the name of Java
can anyone explain the line Thread(this,"Producer");???
"Producer" is the name of thread.
The guy is so confused. Still helpful :p
thank you, guy!
Seems like u know things, but need to practice how to explain things
everything is good i didn't understand value set
Great
thank u sir.... a great explanation .............
java the complete reference ki copy hai yeh line to line code same hai
Give one more example sir
Sir it's too complex program to understand for beginners.
start with easy ones brother by urself.I mean u can try simple thread creation and sleep calls in a simple code then try to figure out whats how this is getting callled and whats happening on method call.
💞💞💞💞💞Awesome 🇮🇳💞💞💞💞
Multithreading in Java by your channel is really poor..no clarity at all.
True I recommend you to read Head First Java multithreading is explained nicely in that book
Why he used Q q ? That's where I didn't get
so that we can use q methods which is get and set
ye chatgpt wale ads block kar do sir, if its possible
hhuh what are you trying to tell us???????
Worst Explanation. Many things are wrong in this example. Refer Java concurrency in practice. Merely getting the right output is not enough in multithreaded programming.
yes i understood that after giving interview in oracle these online videos are somewhat not clear
why are u so confused
Too confusing
the guy is little weak in multi Threading.
among all video this was less understandable.
Didn’t like this video. More I try to understand using this video, more confused I get. Please try to explain the use case first and also do you homework before creating the video so that you don’t have to do so many hit and try in the video.👎
Disappointed
dhang se to padhao sir
kuch smj ni aaya
Just copied the whole thing from herbert manuel book!!! That's why i hate watchting learning videos on youtube. You learn nothings new. :/