读者作家问题并发Java [英] Readers writers problem concurrent Java
问题描述
这是读者作家的一种实现,即许多读者可以阅读,但一次只能有一位作家可以写作。这能按预期工作吗?
This is an implementation of readers writers, i.e. many readers can read but only one writer can write at any one time. Does this work as expected?
public class ReadersWriters extends Thread{
static int num_readers = 0;
static int writing = 0;
public void read_start() throws InterruptedException {
synchronized(this.getClass()) {
while(writing == 1) wait();
num_readers++;
}
}
public void read_end() {
synchronized(this.getClass()) {
if(--num_readers == 0) notifyAll();
}
}
public void write_start() throws InterruptedException{
synchronized(this.getClass()) {
while(num_readers > 0) wait();
writing = 1;
}
}
public void write_end() {
this.getClass().notifyAll();
}
}
此实现与声明每种方法是否有所不同
Also is this implementation any different from declaring each method
public static synchronized read_start()
例如?
谢谢
推荐答案
否-尽管没有在 this
上进行同步,但是您隐式调用 this.wait()
在课堂上。同样,您在 read_end
中调用 this.notifyAll()
。我的建议:
No - you're implicitly calling this.wait()
, despite not having synchronized on this
, but instead on the class. Likewise you're calling this.notifyAll()
in read_end
. My suggestions:
- 不要扩展
Thread
- 不要使用实例成员这样的静态变量;它使外观看起来像是基于每个对象的状态,但实际上没有。我个人只是使用实例变量。
- 不要在名称中使用下划线-常规的Java名称为
numReaders
,readEnd
(或更好的是endRead
)等。 - 不要在
this
或班级上进行同步(如果可以帮助的话)。我个人更喜欢使用private final Object
变量来锁定(并等待等)。这样一来,您就知道只有您的代码可以在其上同步,这使得推理起来更容易。 - 您从不设置
编写
设为0。出于什么原因首先使用整数而不是布尔
?
- Don't extend
Thread
- you're not specializing the thread at all. - Don't use static variables like this from instance members; it makes it look like there's state on a per-object basis, but actually there isn't. Personally I'd just use instance variables.
- Don't use underscores in names - the conventional Java names would be
numReaders
,readEnd
(or better,endRead
) etc. - Don't synchronize on either
this
or the class if you can help it. Personally I prefer to have aprivate final Object
variable to lock on (and wait etc). That way you know that only your code can be synchronizing on it, which makes it easier to reason about. - You never set
writing
to 0. Any reason for using an integer instead of aboolean
in the first place?
当然,最好在框架中使用此类,但我希望您确实是在写这篇文章,以更好地理解线程。
Of course, it's better to use the classes in the framework for this if at all possible - but I'm hoping you're really writing this to understand threading better.
这篇关于读者作家问题并发Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!