jdk1.7

java.lang

String

        /*String aa=new String(); String不可变,构造函数不必要*/
        String a="hello";
        char[] chars=new char[a.length()];

        a.getChars(0,2,chars,0);//截取字符串放到chars数组指定位置
        byte[] bytes = a.getBytes();//将字符串挨个放入字符数组
        a.compareTo("world");//按字典顺序比较两个字符串,一样则返回0
        a.matches("正则表达式");

StringBuilder/StringBuffer

        /**
         *  两者用法一致,但stringbuffer线程安全
         * 
         *  默认初始容量capacity:16
         *  new StringBuffer("hello") capacity=16+"hello".length
         *  new StringBuilder(12)   capacity=12
         */
        StringBuffer stringBuffer = new StringBuffer("hello");
        StringBuilder stringBuilder = new StringBuilder(12);

        stringBuffer.capacity();//获取容量大小
        stringBuffer.trimToSize();//调整容量为字符串所占容量(5)
        /**
         * capacity:长度 * 2 + 2
         * if(capacity>minimumCapacity:10){
         *      capacity=长度 * 2 + 2
         * }else{
         *      capacity=minimumCapacity
         * }
         */
        stringBuffer.ensureCapacity(10);//扩容
        stringBuffer.reverse();//逆向输出
        stringBuffer.toString();//转换为字符串

enum

  1. 简单枚举
      enum SimpleFruites {
            //测试水果枚举
            FRUITS_APPLE,FRUITS_ORANGE, FRUITS_OTHER;
        }
    
        public static void main(String[] args) {
            /* values()方法和valueOf(String name)方法是编译器生成的static方法*/
            // 获取枚举值所有变量,作为一个数组返回
            SimpleFruites[] fruites = SimpleFruites.values();
            // 根据名称获取枚举变量
            SimpleFruites.valueOf("FRUITS_APPLE");
            //获取类名
            fruites[0].getClass();
        }

     

  2. 带参枚举
    public enum DescWeek {
        //带参数枚举
        DESC_MONDAY("一","上班"),DESC_TUESDAY("二","上班"),DESC_THIRSDAY("三","上班"),DESC_FORTHDAY("四","上班"),DESC_FIVEDAY("五","上班"),
        DESC_SATURDAY("六","出去唱歌"),DESC_SUNDAY("天","在家打游戏");
    
        public String code;
        public String desc;
    
        DescWeek(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }
    
    }
       public static void main(String[] args) {
            for (DescWeek day :DescWeek.values()) {
                System.out.println("星期"+day.code+","+day.desc);
            }
        }

     

线程

创建线程的三种方法

  1. 继承Thread
    //FirstThread线程
    public class FirstThread extends Thread {
        @Override
        public void run() {}
    }
    
    
    
    //test
    public static void main(String[] args) {     
            // 调用Thread类public Thread()构造
            Thread thread1=new FirstThread();
            FirstThread thread2=new FirstThread();
    
            //start调用重写的run方法
            thread1.start();
            thread2.start();
    }
  2. 实现runable
    //FirstThread线程
    public class FirstThread implements Runnable {
        @Override
        public void run() {}
    }
    
    
    //test
    public static void main(String[] args) {
            // 调用Thread类public Thread(Runnable target)
            Thread thread1 = new Thread(new FirstThread());
            Thread thread2 = new Thread(new FirstThread());
            thread1.start();
            thread2.start();
    }
    
  3. 创建线程池   

参数:

corePoolSize

核心线程数

maximumPoolSize

最大线程数

keepAliveTime

存活时间

workQueue:

  1. ArrayBlockingQueue

  2. LinkedBlockingQueue

  3. SynchronousQueue

工作队列:

  1. 有界队列,先进先出

  2. 链表队列,先进先出

  3. 将元素放入队列时,如果没有线程等待,ThreadPoolExecutor将创建一个线程, 创建失败则这个任务将被拒绝

创建线程池

   ​
 //最大工作线程数为Integer.MAX_VALUE
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        print(cachedThreadPool);

        //最大工作线程数为3,提交一次任务就创建一个工作线程
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        print(fixedThreadPool);

        //最大工作线程数为1
        ExecutorService singleThread = Executors.newSingleThreadExecutor();
        print(singleThread);

        //最大核心线程5,支持定时及周期性任务执行
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("(3000毫秒)三秒后,任务只会被执行一次");
            }
        }, 3000, TimeUnit.MILLISECONDS);

        scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("延迟三秒,每隔两秒执行一次");
            }
        }, 3000, 2000, TimeUnit.MILLISECONDS);
}

    //打印任务
    public static void print(ExecutorService pool) {
        for (int i = 0; i < 10; i++) {
            //提交执行任务
            pool.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }

​

executorservice方法   提交任务参考:https://blog.csdn.net/u010940300/article/details/50251841

 ExecutorService pool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 5; i++) {
            task(pool);//添加任务
        }

        //线程休眠,可读性更高(内部实现是sleep)
        TimeUnit.MILLISECONDS.sleep(5000);
        pool.shutdownNow();
        /**
         * ExecutorService方法 
         *
         * submit(Runnable task, T result)  提交单个任务,并返回Future(结果)
         * invokeAll(collection,time,TimeUnit.SECONDS)  提交任务集合,所有任务完成或中断或超时,返回Future列表
         * shutdown()   队列任务完成后停止
         * awaitTermination(0,TimeUnit.MILLISECONDS)    shutdown请求后所有任务是否执行完毕
         * shutdownNow()    停止所有任务
         * isTerminated()   池内所有任务是否执行完毕
         *
         *
         */
    }

    public static void task(ExecutorService pool) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("--------执行任务");
            }
        });

    }

线程状态

参考文章:http://www.importnew.com/21136.html

同步锁

sychornized(确定线程共享的资源)

方法加锁和代码块加锁,是当前对象锁

类上加锁和代码块加锁sychornized(类.class),是类锁

    private int ticket=1;//共享资源
    public void run() {
        for (ticket=1; ticket < 5; ticket++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.have();//调用方法            
        }
    }
    
    //方法加锁
    public synchronized void have() {
        if(this.ticket<5){
            System.out.println(Thread.currentThread().getName() + "-----------ticket:" + this.ticket);
        }
    }
    private UserSychornized sc;

    public FirstThread(UserSychornized sc) {
        this.sc = sc;
    }

    public void run() {
        //代码块加锁
        synchronized(this){
                sc.getAge();
            }
    }

sleep

注意:是Thread类的方法

用法:一般用于定时任务,不会释放对象锁

wait

参考实例:https://blog.csdn.net/superit401/article/details/52254087

注意:是Object类方法,必须有对象锁才可以使用wait

用法:wait后释放锁并进入等待池,notify任意一个该等待池的线程进入就绪状态(等待CPU调度)

java.io

/**
 * @author: YANG
 * @create: 2018-08-14 15:13
 * @description: 文件iO写法
 */
public class IoTest {
    public static void main(String[] args) {
        File file = new File("a.txt");
        // \r\n换行
        new IoTest().writein(file,"\r\n在你门撒个娇,哎哟喵喵喵喵喵");
        new IoTest().readit(file);
    }

    void writein(File file, String str) {
        try {
            //在末尾追加字符串
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    void readit(File file) {
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            //一行一行读
            String s;
            /*System.out.println(br.readLine());继续读一行然后输出*/
            while ((s = br.readLine()) != null) {
                //读一行写一行
                System.out.println(s);
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

java.net

socket通信

参考文章:https://www.cnblogs.com/goodboy-heyang/p/6372058.html

参考文章:https://www.cnblogs.com/yiwangzhibujian/p/7107785.html

TCP


 

java.utill

反射

        //通过已有的对象反射创建对象(不经常用)
        Class clazz=u.getClass();//
        try {
            //通过类的路径反射动态加载类(经常用),只完成加载工作和static初始化
            Class cla=Class.forName("javaEE.jdkTest.User");

            //newInstance创建对象,只能调用无参构造函数
            User user= (User) cla.newInstance();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

集合

List接口

        List list=new ArrayList();//默认容量为10,底层数据是数组
        List list1=new LinkedList();//实现Deque接口,是一个双向链表
        for (int i = 97; i < 107; i++) {
            list.add((char)i);
            list1.add((char)i);
        }

        //jdk1.7版本扩容用了位运算
        list.add('z');//默认为原来长度的1.5倍,即现在容量是15
        list1.add('z');

        list.get(5);
        list1.get(5);

Map接口

         /**
         * 加载因子实质:考虑到空间利用率和查询速度的折中
         * 如果factory过大,则空间过大
         * 如果过小,空间小,但是hash冲突几率变大
         * 
         * 什么时候扩容(临界值:16*0.75)
         * hashMap存储的元素个数 > 临界值 ,容量变为16*2,然后重新分配元素位置
         */
        Map<String,String> map=new HashMap<>();//默认容量为16,加载因子为(FACTOR)0.75,
        for (int i = 97; i < 109; i++) {
            for (int j = 0; j < 12; j++) {
                map.put(String.valueOf(j), String.valueOf((char)i));
            }
        }
        map.put("Aa","Aa");//先判断是否已存在该元素(key),若存在则替换value值

        /**
         * 13,14 Hash冲突
         * 如果hashCode冲突,则通过equals判断是否是同一个key
         * 因为String已重写过equals方法,所以一般用string做key
         */
        map.put("BB","BB");

set接口

        Set<String> set=new HashSet<>();//内置hashMap
      

Arrays.sort排序(后补)

Collections.sort底层实现也是Arrays.sort

  int[] arr = new int[46];
        for (int i = 0; i < arr.length - 1; i++) {
            //Math.random()取值范围(0.0 , 1.0],底层实际调用类Random
            //random.nextInt()取值范围[0,40]
            int ranNum = (new Random().nextInt(40));
            arr[i] = ranNum;
        }

        /**
         *  if (length < QUICKSORT_THRESHOLD:286){
         *             DualPivotQuicksort 双基快排
         *                 if(length < INSERTION_SORT_THRESHOLD:47){
         *                     插入排序
         *                 }else{
         *                     快排
         *                 }
         *         }
         */
        //DualPivotQuicksort 双基快排,insertSort(arr)
        Arrays.sort(arr);

        //查找3索引
        Arrays.binarySearch(arr,3);

自定义排序(实现过程一致,都用了Arrays.sort方法)

Comparable需要比较的类实现Comparable接口,需要重写方法

  @Override
    public int compareTo(User o) {
        return this.age-o.age;
    }
      List list=new ArrayList();
        list.add(new User("yang",22,"woman"));
        list.add(new User("mao",22,"woman"));
        list.add(new User("cheng",23,"man"));
        list.add(new User("long",17,"man"));
       
        //User类实现了Comparable接口,自动按照compare规则排序
        Collections.sort(list);
    }

Comparator自己建立比较器

        List list = new ArrayList();
        list.add(new Apple("apple1", "red", 5.50, 0.54));
        list.add(new Apple("apple2", "vivid green", 5.50, 0.34));
        list.add(new Apple("apple3", "red", 2.50, 0.44));
        Collections.sort(list, new Comparator<Apple>() {
            //自定义比较规则
            public int compare(Apple o1, Apple o2) {    
                if (o1.getColor().equals(o2.getColor())) {
                    return o1.getPrice() > o2.getPrice() ? 1 : -1;
                } else {
                    //字符串比较,字典顺序
                    return o1.getColor().compareTo(o2.getColor()) > 0 ? 1 : -1;
                }
            }
        });
    }

java.Math

  //处理大整数,测试Integet最大值
        BigInteger bigInteger=new BigInteger("2147483647");
        System.out.println(bigInteger.negate());

        //精确计算货币值(一般用于商业计算)
        BigDecimal bigDecimal=new BigDecimal("2147483.56434354875415484");
        System.out.println(bigDecimal.add(new BigDecimal("4.1545456895645")));

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值