gpt4 book ai didi

java - 在并发类的 run() 方法中放置什么?

转载 作者:行者123 更新时间:2023-12-01 23:06:47 25 4
gpt4 key购买 nike

假设我们有一个名为 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 的接口(interface) run() 方法中放入什么。如果我想读/写这本书怎么办? run() 如何发挥作用?非常感谢示例。

@Override
public void run() {

// now what???

}

最佳答案

好的,一般而言,您的任务实现了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();

另请注意,代码中的条件并没有真正实现任何目标。

关于java - 在并发类的 run() 方法中放置什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22614284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com