How two different class threads communicate with each
other?. send example code.

Answer Posted / modi[achir communication]

using wait() and notify() two different class threads
communicate with each other.
For example:

public class LoggingThread extends Thread {
private LinkedList linesToLog = new LinkedList();
private volatile boolean terminateRequested;

public void run() {
try {
while (!terminateRequested) {
String line;
synchronized (linesToLog) {
while (linesToLog.isEmpty())
linesToLog.wait();
line = (String) linesToLog.removeFirst();
}
doLogLine(line);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}

private void doLogLine(String line) {
// ... write to wherever
}

public void log(String line) {
synchronized (linesToLog) {
linesToLog.add(line);
linesToLog.notify();
}
}
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

what is singleton in java?

801


What do you understand by the term singleton?

774


Explain about fail safe iterators in java?

788


Explain about complier design(phases)

836


What are disadvantages of java?

752


What is difference between call by value and call by reference?

712


Why volatile is used in java?

751


What is string intern in java?

772


What is an i/o filter?

1188


What are the ways to instantiate the class class?

803


Compare overloading and overriding?

781


What is a Null object?

1202


What is multiple inheritance? Is it supported by java?

723


How do you calculate square roots?

856


why Java does not support multiple inheritances?

918