- 16
- 1月
上周我们进行了最后一周的课程:操作系统课程设计。
这个名字听起来挺吓人,不过实际上比期中的那个系统软件分析与设计简单多了。老师出的题目不过是让实现一个多线程的演示程序。由于只是个演示用途,也没有限制开发环境。但有一点特殊的是这次课程是分组做的,老师按照学生名单每相邻三个人分为一组,完成同一个任务。我被分到和班里学习最好的两个女生一起完成第一道题:演示对两个缓冲区的put、move、get操作。
说实话,不过是一个简单的演示程序。后面用Java的Lock和Condition实现一个buffer的model,用swing做一个图形界面,再写个controller就可以了。上学期编的那个连连看才花了我四天时间。但现在我要和两个女生合作,这个难度可就高了一个数量级。不过毕竟是团队嘛,如果我什么都不管,自己单干的话确实也不是很好(我一哥们选择了这条路,自己单独完成一道题)。
一周的课设下来,大概花了一半的时间解释和讨论程序的思路和实现方法,一半的时间用在编码上。总算在让大家都基本明白程序是怎么回事的基础上完成了设计。而且体会到了给别人讲解确确实实是提升自己理解能力的非常好的方法。
以下是我自己写的缓冲区类,存放自定义的数据类型Data,这个类型里只包括一个整型的id和Color型的随机颜色信息:
package model;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author riqe
* buffer
*/
public class SynchBuffer {
private Data[] buffers;
private int head;
private int rear;
private Lock bufferLock;
private Condition puttable;
private Condition takable;
public Statistic statistic;
public SynchBuffer(int size){
buffers=new Data[size+1];
head=0;
rear=0;
bufferLock=new ReentrantLock();
puttable=bufferLock.newCondition();
takable=bufferLock.newCondition();
statistic=new Statistic();
}
/**
* Put data into the buffer.
* It will cause the calling thread blocked
* when the buffer is being operated or full.
* @param value data to put into the buffer.
* @param delay millisecond to delay after put the data in.
*/
public void put(Data value,int delay){
bufferLock.lock();
try{
while((head-rear+buffers.length)%buffers.length==1)
puttable.await();
buffers[rear]=value;
rear=(rear+1)%buffers.length;
statistic.addPutCount();
takable.signalAll();
Thread.sleep(delay);
}catch (InterruptedException e) {
}finally{
bufferLock.unlock();
}
}
/**
* Take data out of the buffer.
* It will cause the calling thread blocked
* when the buffer is being operated or empty.
* @param delay millisecond to delay after take the data out
* @return
*/
public Data take(int delay){
Data getValue=null;
bufferLock.lock();
try{
while((buffers.length+head-rear)%buffers.length==0)
takable.await();
getValue=buffers[head];
head=(head+1)%buffers.length;
statistic.addTakeCount();
puttable.signalAll();
Thread.sleep(delay);
}catch (InterruptedException e) {
}finally{
bufferLock.unlock();
}
return getValue;
}
/**
* clear up the buffer.
*/
public void sweep(){
bufferLock.lock();
rear=head;
bufferLock.unlock();
}
}
附上这次的成果,jar文件,安装Java Runtime Environment双击即可运行。
双缓冲操作显示