在我的作业中,我需要展示代码中读/写锁和“同步”关键字使用之间的区别。我真的不知道该怎么做,以及理解这种差异的明确方法是什么。我还需要显示以两种方式执行同一任务的时间差。这是我尝试过的代码(虽然没有同步)
public class Main {
public static void main(String[] args) {
Number number = new Number(5);
Thread t1 = new Thread(){
public void run(){
System.out.println(number.getData());
number.changaData(10);
System.out.println(number.getData());
}};
Thread t2 = new Thread(){
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(number.getData());
number.changaData(20);
System.out.println(number.getData());
}};
t2.start();
t1.start();
}
}
public class Number {
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock readLock = rwl.readLock();
private final Lock writeLock = rwl.writeLock();
int value;
public Number(int value) {
this.value = value;
}
public int getData() {
readLock.lock();
try {
return value;
}
finally {
readLock.unlock();
}
}
public int changaData(int change) {
writeLock.lock();
try {
value = change;
return value;
}
finally {
writeLock.unlock();
}
}
}
慕桂英4014372
相关分类