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

Why synchronization is important in java?

558


What is the difference between method overriding and overloading?

571


What is scope of a variable?

603


Define packages in java?

576


what is the difference between Object Based Language and Object Oriented Language?

593






Which is best ide for java?

517


Explain the importance of throws keyword in java?

565


Define max and min heap, also the search time of heap.

584


Explain 5 features introduced in jdk 1.7?

607


What are the differences between Java 1.0 and Java 2.0?

1675


How are observer and observable used in java programming?

541


What is array length in java?

521


What is difference between string and stringbuffer?

490


Explain methods specific to list interface?

551


How do you convert bytes to character in java?

531