Suppose we have a thread-safe class called Teacher which implements Runnable. A teacher can either read or write to a student's book.
public class Teacher implements Runnable {
boolean doneWithBook = false;
private Lock lock = new ReentrantLock();
private Condition cond = lock.newCondition();
public void readBook(Book book) {
lock.lock();
try {
book.read();
doneWithBook = false;
cond.signalAll();
System.out.println("Teacher read the book");
} finally {
lock.unlock();
}
}
public void writeToBook(Book book) {
lock.lock();
try {
book.write();
doneWithBook = true;
System.out.println("Teacher wrote to book.");
} finally {
lock.unlock();
}
}
Teacher implements Runnable, so the task can be ran on its own separate thread. What I don't understand is what to put inside the Runnable's interface run() method. What if I want to read/write to the book. How does run() come into play? Examples are greatly appreciated.
@Override
public void run() {
// now what???
}