java 大文件读者问题,读者作家问题并发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()

for example?

Thanks

解决方案

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:

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 a private 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 a boolean 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值