Comment on Tutorial - wait(), notify() and notifyAll() in Java - A tutorial By Jagan
Comment Added by : Hdm-Student
Comment Added at : 2010-06-16 08:10:51
Comment on Tutorial : wait(), notify() and notifyAll() in Java - A tutorial By Jagan
Hello,
your solution is kinda overkill.
When used correctly, notify and wait don't need workarounds such as valueSet.
Here's the improved version:
----------------------
package producer;
// A correct implementation of a producer and consumer.
class Q {
int n;
synchronized int get() {
try {
notify();
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
try {
notify();
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
System.out.println("Put: " + n);
}
}
public class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while (true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
-------------------------
View Tutorial
- Data Science
- React Native
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Read a file having a list of telnet commands and execute them one by one using Java
Open a .docx file and show content in a TextArea using Java
Step by Step guide to setup freetts for Java
Of Object, equals (), == and hashCode ()
Using the AWS SDK for Java in Eclipse
DateFormat sample program in Java
concurrent.Flow instead of Observable class in Java
Calculator application in Java
Sending Email from Java application (using gmail)