DemoThread.main-->DemoThread.DemoThread()-->create two threads and start them
-->run()(2 start)-->wait()----------------------print notify,wait
-->run()(1 start)-->while(),print(), notify,wait----------------->...Do you forget to call the increaseTime() somewhere?
-->run()(2 start)-->wait()----------------------print notify,wait
-->run()(1 start)-->while(),print(), notify,wait----------------->...Do you forget to call the increaseTime() somewhere?
private LinkedList list = new LinkedList(); public Queue() {
} public synchronized void put(Object v){
list.addFirst(v);
notifyAll();
} public Object get(){
while (true){
synchronized(this){
if ( !isEmpty() )
return list.removeLast();
}
try{
wait();
}catch(Exception e){
System.err.println(e.toString());
}
}
} public boolean isEmpty(){
return list.isEmpty();
} //for debug
public static void main(String[] args) {
Queue queue1 = new Queue(); //queue1.start();
queue1.get();
for(int i=0;i<10;i++)
queue1.put(Integer.toString(i)); while(!queue1.isEmpty())
System.out.println(queue1.get());
}
}中,根本就不对,系统还报错 我该怎么解决?
我的这段代码的目的是实现一个作业队列, 这个队列被一个多线程的服务器应用程序使用,所以我希望这个类的get()函数能够在队列为空的时候停下来等待,而put()函数在添加了一个函数之后能够通知get()方法继续执行下去, 可是... ...
系统报出的错误是:
java.lang.IllegalMonitorStateException: current thread not owner我该怎么写这个类?
public void put(Object v){
synchronized(list) {
list.addFirst(v);
list.notifyAll();
}
} public Object get(){
while (true){
synchronized(list){
if ( !isEmpty() )
return list.removeLast();
}
try{
list.wait();
}catch(Exception e){
System.err.println(e.toString());
}
}
}
下面的代码没有用编译器检验,权当抛砖引玉吧.
//for debug
public static void main(String[] args) {
final Queue queue1 = new Queue();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<10;i++)
queue1.put(Integer.toString(i));
}
}).start(); new Thread(new Runnable() {
public void run() {
while(!queue1.isEmpty())
System.out.println(queue1.get());
}
}).start();
}