Chinaunix首页 | 论坛 | 博客
  • 博客访问: 198745
  • 博文数量: 66
  • 博客积分: 966
  • 博客等级: 准尉
  • 技术积分: 550
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-11 11:52
文章分类

全部博文(66)

文章存档

2012年(60)

2011年(6)

分类: Java

2012-10-11 10:58:34

package read;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
 /*
  * 模拟处理16行日志,下面的代码产生了16个日志对象,当前代码需要运行16秒才能打印完这些日志。
  * 修改程序代码,开四个线程让这16个对象在4秒钟打完。也就是说每秒钟打印4个线程;
 */
 public class Test {
  
  public static void main(String[] args){
   
   final BlockingQueue queue = new ArrayBlockingQueue(16);
   
   for (int i = 0; i < 4; i++) {
    
    new Thread(new Runnable(){
     @Override
     public void run() {
      
      while(true){
       
       String log;
       try {
        log = queue.take();
        parseLog(log);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
     
       
      }
      
     }
    }){}.start();
    
   }
   
   System.out.println("begin:"+(System.currentTimeMillis()/1000));
   for(int i=0;i<16;i++){  //这行代码不能改动
    final String log = ""+(i+1);//这行代码不能改动
    {
          // Test.parseLog(log);
     try {
      queue.put(log);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  }
  
  //parseLog方法内部的代码不能改动
  public static void parseLog(String log){
   System.out.println(log+":"+(System.currentTimeMillis()/1000));
   
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }  
  }
  
 }
 
以上除去红色部分是原题:加上红色代码区就是修改过的程序,此面试题来自张孝祥老师视频讲解,我手炒了一遍,主要知识点是多线程 队列
 
阅读(4841) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~