近日,学校布置了一段用JAVA实现生产者-消费者原理的代码,要求生产者输入一段无大小顺序的数值例如;5,7,8,0,.....然后消费者要按从小到大的顺序读出数值,也以上面那段数值为例子,先要读出5,就要先读出0,如此类推.....然后给出一段代码,我这里只写了一部分,因为太长了....
class Queue
{ List head;
int value;
public List(int n)
{ this.value=n;
this.next=null;
}
}
........请问这里的LIST有什么作用呢?谢谢
class Queue
{ List head;
int value;
public List(int n)
{ this.value=n;
this.next=null;
}
}
........请问这里的LIST有什么作用呢?谢谢
public List(int n)
{ this.value=n;
this.next=null;
}
这里的List(int n )这个构造函数构造了一个连表的头节点。这个题目无非就是连表的排序,删除,插入的一个操作吧
我把余下的一部分程序打一下吧,因为我还有几个问题,也顺便帮我看下有什么地方要改正和改进的,谢谢
.......
public synchronized void read(int n) //消费者读出数据
{ while(!isNonEmpty()||lowestValue()!=n)
{ try{
System.out.println("Consumer hast a rest");
wait();
}
catch(Exception e)
{
System.out.println("break");
e.printStackTrace();
}
}
if(isNonEmpty())
{
if(head.value==n) //这里head是怎么来的?前面并没有声明过.是LIST里面自带的吗?
head=head.next;
else
{ List t=head;
while(t.next!=null)
{
if(t.next.value==n) //t.next.value是什么意思?
{if(t.next==last)
last=t;
t.next=t.next.next;
break; }
}
}
}
public synchronized int lowestValue() \\筛选最小数目的过程
{
if(isNonEmpty())
{
int m=head.value;
List t==head;
while(t!=null)\\ 这个循环有什么用
{
if(t.value<m)
m=t.value;
t=t.next;
}
return m;
else
return -1;\\ 为什么要返回-1
}
.............
class Queue
{
List head;
int value;
public List(int n)
{ this.value=n;
this.next=null;
}
}
类Queue怎么会有名称为List的构造函数?暂时理解为类部类.至少还是不明白.
public synchronized void read(int n) //消费者读出数据
----猜测这是Queue类的一个方法,
{...................
if(head.value==n)//这里head是怎么来的?前面并没有声明过.是LIST里面自带的吗?
----在我这段回复第4行声明了一个叫head的类型为List的对象
..................
if(t.next.value==n) //t.next.value是什么意思?
----按照你的要求猜测List是一个链表,通常链表中会有next,prev来表示下一个和上一个连接的对象,它们通常类型就是当前链表类型,如你这里的List,所以你可以理解为:
List next = t.next;
next.value;while(t!=null)\\ 这个循环有什么用
{
if(t.value<m)
m=t.value;
t=t.next;
}
----这个循环每执行一次对象t被指向它的下一个连接对象,就是t=t.next来处理的,当到最后一个连接并且没有更下一个时t会为null.退出循环,方法lowestValue() \\筛选最小数目的过程
if(isNonEmpty())
----返回链表中的最小数目
否则返回-1.
当你在方法中指定这种方式(返回一个默认值)时,调用这个方法的地方一定要知道返回值是什么意思.
----在我这段回复第4行声明了一个叫head的类型为List的对象" 为什么声明在后面而不是在前面呢?
"if(t.next.value==n) //t.next.value是什么意思?
----按照你的要求猜测List是一个链表,通常链表中会有next,prev来表示下一个和上一个连接的对象,它们通常类型就是当前链表类型,如你这里的List,所以你可以理解为:
List next = t.next;
next.value;"
那是不是说明next不用声明为List next就可以直接用呢?
class QUEUE
{
public void read(int n) {.....}
public int lowestValue() {.....}
public boolean isNotEmpty(){.....}
public void add(Integer n)(){.....}
}
请高手们帮我看看应该怎样写....用多线程来写.....
class Queue
{
classs Node
Node head;
int value;
public Node(int n)
{ this.value=n;
this.next=null;
}
}.............
class QUEUE
{
public void read(int n) {.....}
public int lowestValue() {.....}
public boolean isNotEmpty(){.....}
public void add(Integer n)(){.....}
}
请高手们帮我看看应该怎样写....用多线程来写.....