list是ArrayList类的对象
F类要每隔几秒就往里写东西,
A类要每隔几秒都读取list,并会删除里面的数据
G类要每隔一秒都读取list,并显示出来。
F类和A类分别起一个线程,同时执行,对list操作请问要怎么设计?list要放在哪里?其实我在做操作系统的实验,磁盘移臂调度算法。F类模拟动态生成对磁盘的访问请求,A类模拟调度算法选择一个请求执行。
G类就是GUI了,要动态显示请求的生成与相应。list里面装的就是多个请求。
F类要每隔几秒就往里写东西,
A类要每隔几秒都读取list,并会删除里面的数据
G类要每隔一秒都读取list,并显示出来。
F类和A类分别起一个线程,同时执行,对list操作请问要怎么设计?list要放在哪里?其实我在做操作系统的实验,磁盘移臂调度算法。F类模拟动态生成对磁盘的访问请求,A类模拟调度算法选择一个请求执行。
G类就是GUI了,要动态显示请求的生成与相应。list里面装的就是多个请求。
几个thread里有他一个引用,用来加锁
还有,A类和F类里面有一个While循环,对list不断调用,要是在main里建立list,怎么引用?啊!!!!!!!!
或者这样吧,用单态模式进行也应该是可以的吧
private List l;
public ThreadA(List l){
this.l = l;
}
public void run(){
while (true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(l){
l.add(new String("Something"));
}
}
}
}
public class ThreadF implements Runnable{
private List l;
public ThreadF(List l){
this.l = l;
}
public void run(){
while (true){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(l){
if (!l.isEmpty()){
Object o = l.remove(0);
}
}
}
}
}
public class ThreadG implements Runnable { private List l;
public ThreadG(List l){
this.l = l;
}
public void run(){
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(l){
for(Object o:l){
System.out.println(o);
}
System.out.println("Length:"+l.size());
}
}
}
public static void main(String[] args) throws InterruptedException{
List l = new ArrayList();
Thread threadA = new Thread(new ThreadA(l));
Thread threadF = new Thread(new ThreadF(l));
Thread threadG = new Thread(new ThreadG(l));
threadA.setDaemon(true);
threadF.setDaemon(true);
threadG.setDaemon(true);
threadA.start();
threadF.start();
threadG.start();
Thread.sleep(60000);
}
}
生产者线程、消费者线程