1 public enum Index { 2 ZERO(0), 3 ONE(1), 4 TWO(2); 5 6 private int index; 7 8 Index(int index) { 9 this.index = index; 10 } 11 12 public int getIndex() { 13 return index; 14 } 15 }
1 public class ScheduledThreadPoolTest { 2 public static void main(String[] args) throws InterruptedException { 3 // 创建大小为5的线程池 4 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); 5 6 for (int i = 0; i < 3; i++) { 7 Task worker = new Task("task-" + i); 8 // 只执行一次 9 // scheduledThreadPool.schedule(worker, 5, TimeUnit.SECONDS); 10 // 周期性执行,每5秒执行一次 11 scheduledThreadPool.scheduleAtFixedRate(worker, 0,5, TimeUnit.SECONDS); 12 } 13 Thread.sleep(10000); 14 15 System.out.println("Shutting down executor..."); 16 // 关闭线程池 17 scheduledThreadPool.shutdown(); 18 boolean isDone; 19 // 等待线程池终止 20 do { 21 isDone = scheduledThreadPool.awaitTermination(1, TimeUnit.DAYS); 22 System.out.println("awaitTermination..."); 23 } while(!isDone); 24 System.out.println("Finished all threads"); 25 } 26 }
1 class Task implements Runnable { 2 private String name; 3 4 public Task(String name) { 5 this.name = name; 6 } 7 8 @Override 9 public void run() { 10 System.out.println("name = " + name + ", startTime = " + new Date()); 11 try { 12 Thread.sleep(1000); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 System.out.println("name = " + name + ", endTime = " + new Date()); 17 } 18 }
1 Integer total = 99;//自动装箱 2 int totalprim = total;//自动拆箱
自动装箱拆箱的类型为八种基本类型:
String:不可变长的字符序列;
StringBuffer:可变的字符序列,线程安全,效率低;
StringBuilder:可变的字符序列,线程不安全,效率高。
为了共用一套代码:
1 public class PetFactory { 2 private PetFactory() { 3 } 4 public static Pet getPet(String type) throws Exception { 5 Pet pet = null; 6 switch (type) { 7 case "dog": 8 pet = new Dog(); 9 break; 10 case "cat": 11 pet = new Cat(); 12 break; 13 default: 14 throw new Exception(); 15 } 16 return pet; 17 } 18 } 19 public void example(String type){ 20 Pet pet = PetFactory.getPet(type); //向上转型 21 playWithPet(pet);//公共的 22 if(pet instanceOf Dog){ 23 Dog snoopy = (Dog) pet; //向下转型 24 snoopy.sitDown(); 25 } else { 26 Cat white = (Cat) pet; //向下转型 27 white.climb(); 28 } 29 }
编译后的内部类和外部类各一个class文件,内部类访问外部类局部变量实际是复制了一份,为了避免数据的不一致性,设置局部变量为final。
Class文件由类装载器装载后,在JVM中将形成一份描述Class结构的元信息,通过该元信息可以获知Class的结构信息:如构造函数,属性和方法等,Java允许用户通过元信息间接调用Class对象的功能。
在Java中,类装载器把一个类装入JVM中,要经过以下步骤:
类加载器有加载类的需求时,先请求父加载器帮忙加载,直到传到顶层启动类加载器,父加载不了再由子加载器加载;
为了避免重复加载,父加载器加载过了子加载器就没必要再加载了,否则我们可以随时使用自定义的类代替Java核心API中的类型,好阔怕
为了明确职责、增加扩展性(只需要丰富代理功能而不用修改自己方法的代码),把自己需要但是不适合自己做的东西交给代理来做;
比如常见的两类情况:
(a) 在一个类调用前和调用后搞些事情,比如权限控制、日志打印等;
(b) 客户端无法直接操作对象,需要通过网络来访问,可以建立远程对象的代理,像调用本地方法一样调用远程对象等
原文:https://www.cnblogs.com/lcmichelle/p/10743330.html