假设我们有一个名为Teacher的线程安全类,它实现了Runnable。老师可以读或写一本学生的书。
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实现了Runnable,因此任务可以在自己独立的线程上运行。我不明白的是将什么放在Runnable的界面run()方法中。如果我想读/写本书怎么办? run()如何发挥作用?非常感谢例子。
@Override
public void run() {
// now what???
}
答案 0 :(得分:2)
好的,一般而言,这是您的任务实施Runnable
,所以在您的情况下,您可能会有以下内容:
public ReadTask implements Runnable
{
private Teacher teacher;
public ReadTask(Teacher teacher)
{
this.teacher = teacher;
}
public void run()
{
teacher.readBook();
}
}
public WriteTask implements Runnable
{
private Teacher teacher;
public WriteTask (Teacher teacher)
{
this.teacher = teacher;
}
public void run()
{
teacher.writeToBook();
}
}
然后你调用代码看起来像这样:
Teacher teacher = ...
new Thread(new ReadTask(teacher)).start();
new Thread(new WriteTask(teacher)).start();
另请注意,代码中的Condition
并未真正实现任何目标。
答案 1 :(得分:1)
如果我想读/写本书怎么办? run()如何发挥作用?
所以有几种方法可以做到这一点。最简单的方法是在run()
方法中根据某种构造函数参数得到if
:
private final boolean reading;
public Teacher(boolean reading) {
this.reading = reading;
}
public void run() {
if (reading) {
readBook(book);
} else {
writeToBook(book);
}
}
但是,如果读写代码不共享任何代码,那么我会有一个ReadingTeacher
类和一个WritingTeacher
类来执行不同的操作。那么你就可以这样做:
public class ReadingTeacher implements Runnable {
...
public void run() {
readBook(book);
}
}
所有这些都说,我相信你的问题是有条件的。如果您有2个不同的Runnable
个对象,则需要共享相同的条件。应该在线程的外部创建条件并传递给构造函数。然后,阅读教师可以在写作教师正在等待的相同的条件对象上发出信号。
public class Teacher implements Runnable {
private final boolean reading;
private final Condition cond;
public Teacher(boolean reading, Condition cond) {
this.reading = reading;
this.cond = cond;
}
public void run() {
if (reading) {
readBook(book);
} else {
writeToBook(book);
}
}
}
...
Condition cond = lock.newCondition();
new Thread(new Teacher(true, cond)).start();
new Thread(new Teacher(false, cond)).start();
更简化的解决方案是将Condition cond
设为static
,以便所有实例共享相同的条件,尽管这不是一个好的模式。