2 aiguoyigeren aiguoyigeren 于 2014.05.05 20:27 提问

java synchronized问题 求指导

import java.util.LinkedList;
public class Test3 {
LinkedList storage= new LinkedList();
int max=10;
public Test3()
{
}
public void start(){
new product().start();
new c().start();
}
class product extends Thread{
public void run(){
while(true){
synchronized (storage) {
while(storage.size()==max){
System.out.println("仓库满了,你不要生产了");
try {
storage.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

                    }
                   Object o=new Object();
                   if(storage.add(o)){
                       System.out.println("继续生产,往仓库里放");
                       try {
                        Thread.sleep(1000);
                        storage.notify();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                   }    
               }
           }
       }
 }

 class c extends Thread{
       public void run(){
           while(true){
               synchronized (storage) {
               while(storage.size()==0){
                    System.out.println("仓库空了");
                    try {
                        storage.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                storage.removeLast();

                System.out.println("正在取出");
                try {
                Thread.sleep(2000);
                    storage.notify();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
           }
       }
 }
 public static void main(String[] args) {
     Test3 t=new Test3();
     t.start();
}

}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!