易截截图软件、单文件、免安装、纯绿色、仅160KB

java生产者消费者

题目:请用多线程实现一个生产者类和一个消费者类,生产者随机生成20个字符,消费者将字符打印到控制台。
class SyncStack{ //同步堆栈类
   private int index = 0; //堆栈指针初始值为0
   private char []buffer = new char[6]; //堆栈有6个字符的空间
   public synchronized void push(char c){ //加上互斥锁
     while(index = = buffer.length){ //堆栈已满,不能压栈
     try{
        this.wait(); //等待,直到有数据出栈
       }catch(InterruptedException e){}
       }
   this.notify(); //通知其它线程把数据出栈
   buffer[index] = c; //数据入栈
   index++; //指针向上移动
   }
   public synchronized char pop(){ //加上互斥锁
       while(index ==0){ //堆栈无数据,不能出栈
        try{
           this.wait(); //等待其它线程把数据入栈
        }catch(InterruptedException e){}
          }
       this.notify(); //通知其它线程入栈
       index- -; //指针向下移动
       return buffer[index]; //数据出栈
    }
       }
    class Producer implements Runnable{ //生产者类
       SyncStack theStack;
        //生产者类生成的字母都保存到同步堆栈中
       public Producer(SyncStack s){
          theStack = s;
       }
       public void run(){
          char c;
          for(int i=0; i<20; i++){
            c =(char)(Math.random()*26+'A');
                          //随机产生20个字符
            theStack.push(c); //把字符入栈
            System.out.println("Produced: "+c); //打印字符
            try{
            Thread.sleep((int)(Math.random()*1000));
                     /*每产生一个字符线程就睡眠*/
            }catch(InterruptedException e){}
          }
       }
     }
   


相关文档:

Java压缩类库的使用 2.JDK中的打包、压缩类库

  inkfish原创,请勿商业性质转载,转载请注明来源(http://blog.csdn.net/inkfish)。
  这里忽略了jar,因为jar实质上属于zip压缩。(来源:http://blog.csdn.net/inkfish)
JDK ZLIB压缩:(来源:http://blog.csdn.net/inkfish)
package study.inkfish.compress;
import java.io.BufferedInputStream;
import ......

Java压缩类库的使用 3.Apache Ant中的打包、压缩类库

  inkfish原创,请勿商业性质转载,转载请注明来源(http://blog.csdn.net/inkfish)。
  这里需要关注的是BZIP2格式,经过测试,总是无法正确压缩,原因未知,而apache commons bzip2格式的文件压缩正常。(来源:http://blog.csdn.net/inkfish)
Ant ZIP压缩:(来源:http://blog.csdn.net/inkfish)
package stu ......

Java压缩类库的使用 5.性能检测

  inkfish原创,请勿商业性质转载,转载请注明来源(http://blog.csdn.net/inkfish
)。
  在选择压缩、打包算法的时候,不仅仅要选择算法,还需要选择用哪个实现类库,不同的实现类库实现效率不同,默认压缩比率不同。为了测试JDK、Ant、commons-compress在默认情况下的效率,设计了如下程序:(来源:http://blog.c ......

java学习笔记struts action初始化时间和次数

大家都知道 action配置在struts-config.xml中,而struts-config.xml是在tomcat启动时读取的那action是不是在这个时候初始化的
我们可以在action类里进行测试 在构造函数里打印一句话 经测试action是在调用action时初始化,并且多次调用只初始化一次,
这也就是所有的请求共享action实例
所以action是线程不安全的, ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号