美文网首页java 知识点
Java 必备面试代码

Java 必备面试代码

作者: Tim在路上 | 来源:发表于2020-05-08 17:38 被阅读0次

    1. Thread 创建线程

    public Class MyThread extends Thread{   
        public void run(){
    
            System.out.println("aaa");           
        }
    }
    
    public Class Main{
        public static void main(String[] args){
             MyThread t = new MyThread();
                         t.start();
                    }
    }
    

    2. Runnable 创建线程

    public Class ThreadTask implements Runnable{
        
    
        public void run(){
    
            System.out.println("aaa");           
        }
    } 
    
    
    public Class Main{
        public static void main(String[] args){
             ThreadTask task = new ThreadTask();
             Thread t = new Thread(task);
                         thread.start();
                    }
    }
    
    1. 使用线程池创建多线程Callable
    public MyCallable implements Callable<String>{
        public String call(){
                          System.out.println("call");
                          return "call";
                    }
    }
    
    public Class Main{
        public static void main(String[] args){
              ExecutorService pool = new Executor.newFixedThreadPool(taskSize);
                          List<Future>  list  = new ArrayList<Future>();
                          for(int i=0;i<taskSize;i++){
                                    Callable c = new MyCallable(i + " ");
                            Future f = pool.submit(c);
                                    list.add(f); 
                         }
                         // 关闭线程池
                         pool.shutdown();
                         //获取并发任务的运行结果
                        for(Future f :list){
                        System.out.println("res " + f.get().toString());
                         }
        }
    }
    

    4. 基于线程池 创建多线程

    public Class Main{
               public static void main(String[] args){
                       ExecutorService pool = Executors.newFixedThreadPool(10);
                       while(true){
                             Runnable r = new MyRunnable();
                             pool.execute(r);
                       }
               }
    }
    

    5. 创建3线程 1 打印 123,2 打印 456, 3 打印 789

    public ThreadTask {
          // 打印序号
          private int no = 1;
          //  线程维持的序号状态
          private int status = 0;
          
          public  synchronized void print(String threadNo){
              int threadIndex = Integer.parseInt(threadNo);
              // 检验线程的顺序
              while(threadIndex != status){
                   try{
                           this.wait();
        }catch(InterruptedException e){
                           e.printStackTrace();
        }
              } 
             // 每个线程每次打印的个数
              for(int count = 0;count < 5;count ++,no ++){
                      if(count > 0){
                           System.out.print(",");
                      }
                      System.out.print(no)
              }
              System.out.println()
              status = (status + 1) % 3;
              // 唤醒其他线程
              this.notifyAll();
          }
    } 
    
    public class Problem02{
          public static void main(String[] args){
                     ThreadTask task = new ThreadTask();
                     for(int i =0;i<3;i++){
                          new Thread(new Runnable(){
                            public void run(){
                                     // 每一个线程打印的次数
                                     for(int j=0;j<5;j++){
                                            task.print(Thread.currentThread().getName());
                                     }
                               }
                           }) ;
                     }
           }
    }
    

    6. 创建多线程火车票买票系统

    public Class SellTackets implements Runnable{
            private int tackets = 100;
            private Object  lock = new Object();
            
            public void run(){
                   while(true){
                           synchronized(lock){
                                     if(tackets > 0){
                                            System.out.println(Thread.currentThread().getName() + "  : " + tackets -- + " " );
                                     }else{
                                        break;
                                    }
                           }
                   }
            }
    }
    

    // 使用 lock 进行加锁

    public Class SellTackets implements Runnable{
            private int tackets = 100;
            private Lock lock = new ReentrantLock();
            
            public void run(){
                   while(true){
                            try{
                                     lock.lock();
                                     if(tackets > 0){
                                            System.out.println(Thread.currentThread().getName() + "  : " + tackets -- + " " );
                                     }else{
                                        break;
                                    }
                           }finally{
                                   lock.unlock();
                          }
                   }
            }
    }
    

    7. 生产者与消费者

    public class cache {
              private static final int MAX_PRODUCT = 20;
              private int cacheSzie = 0;
              private Object lock = new Object();
              public Cache(int size){
                 this.cacheSize = size;
             }
      
             public void produce(){
                       synchronized(lock){
                            while(cacheSize >= MAX_PRODUCT){
                                  try{
                                       lock.wait();
                                   }catch(InterruptedException e){
                                    e.printStackTrace();
                                   }
                            }
                           cacheSize ++;
                           lock.notifyAll();
                      }
             }
    
           public void consumer(){
                  synchronized(lock){
                        while(cache <= 0){
                                try{
                                       lock.wait();
                                }catch(InterruptException e){
                                     e.printStackTrace();
                               }
                        }
                       cacheSize --;
                       lock.notifyAll();
                   }
           }
    }
    
    public Class Produce{
             private Cache cache;
             public Produce(Cache cache){
        this.cache = cache;
             }
             public void run(){
                    while(true){
                        cache.produce();
                    }
              }
    }
    
    public Class Consumer{
             private Cache cache;
             public Consumer(Cache cache){
        this.cache = cache;
             }
             public void run(){
                    while(true){
                        cache.consumer();
                    }
              }
    }
    

    // 使用 ReentrantLock() 实现生产者与消费者

    public class cache {
              private static final int MAX_PRODUCT = 20;
              private int cacheSzie = 0;
              private Lock lock = new ReentrantLock();
              private Condition consumerList = null;
              private Condition produceList = null;
              public Cache(int size){
                 this.cacheSize = size;
                 consumerList = new Condition();
                 produceList  = new Condition();
             }
      
             public void produce(){
                            lock.lock();
                            if(cacheSize >= MAX_PRODUCT){
                                  try{
                                       produceList .await();
                                   }catch(InterruptedException e){
                                    e.printStackTrace();
                                   }
                            }
                           cacheSize ++;
                           produceList .signalAll();
                          lock.unlock();
             }
    
           public void consumer(){
                        lock.lock()
                        while(cache <= 0){
                                try{
                                       consumerList .await();
                                }catch(InterruptException e){
                                     e.printStackTrace();
                               }
                        }
                       cacheSize --;
                       consumerList .signalAll();
                       lock.unlock();
                   }
           }
    }
    
    

    1. 通过JAVA 反射实现对象的浅拷贝

      public static Object copy(Object source) throws Exception{
    
            Object o = null;
            Class clazz = source.getClass();
            o = clazz.newInstance();
            while(clazz != Object.class){
    
                Field fields[] = clazz.getDeclaredFields();
                for(Field field : fields) {
                    if(Modifier.isStatic(field.getModifiers()))
                        continue;
                    field.setAccessible(true);
                    Object value = field.get(source);
                    // 基本类型
                    if(field.getType().isPrimitive()) {
                        field.set(o, value);
                    }
                    // 这行就是深度拷贝,否则浅拷贝
                    // 不为null的对象
                    else if(value instanceof Object) {
                        field.set(o, copy(value));
                    }
                    field.setAccessible(false);
                }
                clazz = clazz.getSuperclass();
            }
            return o;
        }
    

    // 通过实现序列化和IO流来实现深度copy

    public static Object deepCopy(Object o) throws IOException, ClassNotFoundException {
    //      //先序列化,写入到流里
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(o);
            //然后反序列化,从流里读取出来,即完成复制
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(bi);
            return oi.readObject();
        }
    
    

    2. 遍历指定目录下的所有文件

    public class FileDemo4 {
        
        public static void main(String[] args) {
             
            File srcFolder = new File("D:\\");
            
            getAllClassFilesPath(srcFolder);
            
        }
    
        private static void getAllClassFilesPath(File srcFolder) {
            try {
                
                //获得当前目录下的所有文件夹
                File[] files = srcFolder.listFiles();
                //遍历files对象
                for (File file : files) {
                    //判断当前是否为文件夹
                    if(file.isDirectory()){
                        getAllClassFilesPath(file);
                    }else{
                        if(file.getName().endsWith(".class")){
                                                file.renameTo(new File("f:/a/b.xlsx"));
                            System.out.println(file.getAbsolutePath());
                        }
                    }
                }
            } catch (Exception e) {
                e.getMessage();
            }
            
        }
    
    }
    
    

    3.多级文件夹的复制

    public class copy {
        
         public static void main(String[] args) {
            //数据源
             File srcFolder = new File("H:\\java");
             //目的地
             File destFolder = new File("F:\\");
             //复制多级文件
             try {
                copyFollder(srcFolder,destFolder);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        private static void copyFollder(File srcFolder, File destFolder) throws Exception {
            
            if(srcFolder.isDirectory()){
                String newname = srcFolder.getName();
                File newFolder = new File(destFolder,newname);
                newFolder.mkdir();
                File[] files = srcFolder.listFiles();
                for (File file : files) {
                    copyFollder(file, newFolder);
                }
                
            }else{
                File newFile = new File(destFolder,srcFolder.getName());
                copyFile(srcFolder,newFile);
            }
        }
    
        private static void copyFile(File srcFolder, File newFile) throws IOException {
            //数据源
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFolder));
            //目的地
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
            //字节数组复制
            byte[] bs = new byte[1024];
            
            while(bis.read(bs)!=-1){
                bos.write(bs);
                bos.flush();
            }
            //释放资源
            bos.close();
            bis.close();
        }
    
    }
    

    System.currentTimeMillis();

    4.将文本中的字符排序后加入到另一个文本中

    /**

    • 1.已知s.txt文件中有一个字符串“ndjdnsnakdapiiisnjvmsdsiajdsailn”;
    • 2.读取文件的内容,存储到字符串中
    • 3.把字符串转化为字符数组
    • 4.对字符数组进行排序
    • 5.把字符数组转化为字符串
    • 6.通过字符输出流把字符串输出到ss.txt

    */

    public class StringArray {
        
           public static void main(String[] args) throws IOException {
             //1. 封装路径
               File srcFolder = new File("H:\\s.txt");
               File destFolder = new File("H:\\ss.txt");
             //字符读取流
               BufferedReader br = new BufferedReader(new FileReader(srcFolder));
             //读取字符串
               StringBuilder sb = new StringBuilder();
               String line = null;
              while((line = br.readLine())!=null){
                  sb.append(line);
              }
             //字符串转化为字符数组
              char[] arrays = sb.toString().toCharArray();
             //将字符数组进行排序
              Arrays.sort(arrays);
             //将字符数组转化为字符串
              String str = String.valueOf(arrays);
              System.out.println(str);
             //建立输出流输出
              BufferedWriter bw = new BufferedWriter(new FileWriter(destFolder));
              bw.write(str);
              bw.flush();
              bw.close();
        }
    }
    

    相关文章

      网友评论

        本文标题:Java 必备面试代码

        本文链接:https://www.haomeiwen.com/subject/bmcqnhtx.html