线程

线程基础

继承Thread

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new MyThread("线程A").start();
  4. new MyThread("线程B").start();
  5. new MyThread("线程C").start();
  6. }
  7. }
  8. class MyThread extends Thread {
  9. private String title;
  10. public MyThread(String title) {
  11. this.title = title;
  12. }
  13. public void run() {
  14. for (int i = 0; i < 10; i++) {
  15. System.out.println(title + ":" + i);
  16. }
  17. }
  18. }

实现Runnable

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new Thread(new MyThread("线程A")).start();
  4. new Thread(new MyThread("线程B")).start();
  5. new Thread(new MyThread("线程C")).start();
  6. }
  7. }
  8. class MyThread implements Runnable {
  9. private String title;
  10. public MyThread(String title) {
  11. this.title = title;
  12. }
  13. public void run() {
  14. for (int i = 0; i < 10; i++) {
  15. System.out.println(title + ":" + i);
  16. }
  17. }
  18. }

Lambda简写

  1. public class Demo {
  2. public static void main(String[] args) {
  3. for(int j=0; j<3; j++) {
  4. String title = "线程" + j;
  5. new Thread(()->{
  6. for (int i = 0; i < 10; i++) {
  7. System.out.println(title + ":" + i);
  8. }
  9. }).start();
  10. }
  11. }
  12. }

实现Callable

  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.FutureTask;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. FutureTask<String> task = new FutureTask<String>(new MyThread());
  6. new Thread(task).start();
  7. System.out.println(task.get());
  8. }
  9. }
  10. class MyThread implements Callable<String> {
  11. public String call() throws Exception {
  12. for (int i = 0; i < 10; i++) {
  13. System.out.println("线程执行:" + i);
  14. }
  15. return "线程执行完成";
  16. }
  17. }

线程常用方法

获取线程名称

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new Thread(new MyThread(),"线程A").start();
  4. new Thread(new MyThread()).start();
  5. new Thread(new MyThread()).start();
  6. new Thread(new MyThread(),"线程B").start();
  7. }
  8. }
  9. class MyThread implements Runnable {
  10. public void run() {
  11. System.out.println(Thread.currentThread().getName());
  12. }
  13. }

线程休眠

  1. public class Demo {
  2. public static void main(String[] args) {
  3. new Thread(new MyThread()).start();
  4. }
  5. }
  6. class MyThread implements Runnable {
  7. public void run() {
  8. System.out.println(Thread.currentThread().getName());
  9. try {
  10. Thread.sleep(3000);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. System.out.println("OK");
  15. }
  16. }

线程中断

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Thread thread = new Thread(new MyThread());
  4. thread.start();
  5. Thread.sleep(1000);
  6. thread.interrupt();
  7. }
  8. }
  9. class MyThread implements Runnable {
  10. public void run() {
  11. try {
  12. System.out.println(Thread.currentThread().getName());
  13. Thread.sleep(3000);
  14. System.out.println("OK");
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. }

强制执行

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Thread mainThread = Thread.currentThread();
  4. new Thread(()-> {
  5. try {
  6. for(int i=0; i<20; i++) {
  7. if(i == 5) mainThread.join();
  8. Thread.sleep(100);
  9. System.out.println(Thread.currentThread().getName() + ":" + i);
  10. }
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }).start();
  15. for(int i=0; i<20; i++) {
  16. Thread.sleep(100);
  17. System.out.println(Thread.currentThread().getName() + ":" + i);
  18. }
  19. }
  20. }

线程礼让

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. new Thread(()-> {
  4. try {
  5. for(int i=0; i<20; i++) {
  6. if(i%3 == 0) {
  7. Thread.yield();
  8. System.out.println("礼让");
  9. }
  10. Thread.sleep(100);
  11. System.out.println(Thread.currentThread().getName() + ":" + i);
  12. }
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }).start();
  17. for(int i=0; i<20; i++) {
  18. Thread.sleep(100);
  19. System.out.println(Thread.currentThread().getName() + ":" + i);
  20. }
  21. }
  22. }

线程优先级

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. for(int j=0; j<3; j++) {
  4. Thread thread = new Thread(()-> {
  5. for(int i=0; i<100; i++) {
  6. System.out.println(Thread.currentThread().getName() + ":" + i);
  7. }
  8. });
  9. if(j == 2) {
  10. thread.setPriority(Thread.MAX_PRIORITY);
  11. }else {
  12. thread.setPriority(Thread.MIN_PRIORITY);
  13. }
  14. thread.start();
  15. }
  16. }
  17. }

同步

同步代码块

  1. public class Demo {
  2. public static void main(String[] args) {
  3. MyThread myThread = new MyThread();
  4. new Thread(myThread).start();
  5. new Thread(myThread).start();
  6. new Thread(myThread).start();
  7. }
  8. }
  9. class MyThread implements Runnable {
  10. private int count = 10;
  11. public void run() {
  12. for (int i = 0; i < 10; i++) {
  13. try {
  14. synchronized (this) {
  15. Thread.sleep(100);
  16. if (count == 0) break;
  17. System.out.println(Thread.currentThread().getName() + ":" + count);
  18. count--;
  19. }
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }
  25. }

同步方法

  1. public class Demo {
  2. public static void main(String[] args) {
  3. MyThread myThread = new MyThread();
  4. new Thread(myThread).start();
  5. new Thread(myThread).start();
  6. new Thread(myThread).start();
  7. }
  8. }
  9. class MyThread implements Runnable {
  10. private int count = 10;
  11. private synchronized boolean fun() {
  12. try {
  13. Thread.sleep(100);
  14. if (count == 0) return true;
  15. System.out.println(Thread.currentThread().getName() + ":" + count);
  16. count--;
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }
  20. return false;
  21. }
  22. public void run() {
  23. for (int i = 0; i < 10; i++) {
  24. if(fun()) break;
  25. }
  26. }
  27. }

死锁

  1. public class Demo implements Runnable {
  2. private Jian jian = new Jian();
  3. private Qiang qiang = new Qiang();
  4. public static void main(String[] args) {
  5. new Demo();
  6. }
  7. public void run() {
  8. jian.say(qiang);
  9. }
  10. public Demo() {
  11. new Thread(this).start();
  12. qiang.say(jian);
  13. }
  14. }
  15. class Jian {
  16. public synchronized void say(Qiang qiang) {
  17. System.out.println("Jian要过去");
  18. qiang.get();
  19. }
  20. public synchronized void get() {
  21. System.out.println("Jian过去了");
  22. }
  23. }
  24. class Qiang {
  25. public synchronized void say(Jian jian) {
  26. System.out.println("Qiang要过去");
  27. jian.get();
  28. }
  29. public synchronized void get() {
  30. System.out.println("Qiang过去了");
  31. }
  32. }

生产者消费者

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Meaasge meaasge = new Meaasge();
  4. for (int i = 1; i <= 3; i++) {
  5. new Thread(new Consumer(meaasge), "Consumer" + i).start();
  6. }
  7. for (int i = 1; i <= 3; i++) {
  8. new Thread(new Producer(meaasge), "Producer" + i).start();
  9. }
  10. }
  11. }
  12. // 消息
  13. class Meaasge {
  14. private String contents;
  15. private boolean available = false;
  16. public synchronized void get() {
  17. while (available == false) {
  18. try {
  19. wait();
  20. } catch (InterruptedException e) {
  21. }
  22. }
  23. available = false;
  24. System.out.println(Thread.currentThread().getName() + "消费:" + contents);
  25. notifyAll();
  26. }
  27. public synchronized void put(String value) {
  28. while (available == true) {
  29. try {
  30. wait();
  31. } catch (InterruptedException e) {
  32. }
  33. }
  34. contents = value;
  35. available = true;
  36. System.out.println(Thread.currentThread().getName() + "生产:" + contents);
  37. notifyAll();
  38. }
  39. }
  40. // 消费者
  41. class Consumer implements Runnable {
  42. private Meaasge meaasge;
  43. public Consumer(Meaasge meaasge) {
  44. this.meaasge = meaasge;
  45. }
  46. public void run() {
  47. for (int i = 0; i < 5; i++) {
  48. meaasge.get();
  49. }
  50. }
  51. }
  52. // 生产者
  53. class Producer implements Runnable {
  54. private Meaasge meaasge;
  55. public Producer(Meaasge meaasge) {
  56. this.meaasge = meaasge;
  57. }
  58. public void run() {
  59. for (int i = 0; i < 5; i++) {
  60. meaasge.put(String.valueOf(Math.random()));
  61. try {
  62. Thread.sleep((int) (Math.random() * 500));
  63. } catch (Exception e) {
  64. }
  65. }
  66. }
  67. }

停止线程

  1. public class Demo {
  2. private static boolean flag = true;
  3. public static void main(String[] args) throws Exception {
  4. new Thread(new Runnable() {
  5. public void run() {
  6. while (flag) {
  7. try {
  8. Thread.sleep(1000);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println(Math.random());
  13. }
  14. }
  15. }, "执行线程").start();
  16. Thread.sleep(4000);
  17. flag = false;
  18. }
  19. }

守护线程

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Thread userThread = new Thread(new Runnable() {
  4. public void run() {
  5. for (int i = 0; i < 10; i++) {
  6. try {
  7. Thread.sleep(500);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. System.out.println(Thread.currentThread().getName() + i);
  12. }
  13. }
  14. }, "用户线程");
  15. Thread daemonThread = new Thread(new Runnable() {
  16. public void run() {
  17. for (int i = 0; i < 100; i++) {
  18. try {
  19. Thread.sleep(500);
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. System.out.println(Thread.currentThread().getName() + i);
  24. }
  25. }
  26. }, "守护线程");
  27. daemonThread.setDaemon(true);
  28. daemonThread.start();
  29. userThread.start();
  30. }
  31. }

volatile关键字

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. MyThread myThread = new MyThread();
  4. new Thread(myThread, "卖票线程A:").start();
  5. new Thread(myThread, "卖票线程B:").start();
  6. new Thread(myThread, "卖票线程C:").start();
  7. new Thread(myThread, "卖票线程D:").start();
  8. new Thread(myThread, "卖票线程E:").start();
  9. }
  10. }
  11. class MyThread implements Runnable {
  12. // volatile表示直接操作内存,不用拷贝数据计算后再赋值回去,它没有synchronized的功能
  13. private volatile int ticket = 5;
  14. public void run() {
  15. synchronized (this) {
  16. if (ticket > 0) {
  17. try {
  18. Thread.sleep(100);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. System.out.println(Thread.currentThread().getName() + ticket);
  23. ticket--;
  24. }
  25. }
  26. }
  27. }

基础类库

字符串

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. // 字符串
  4. String str = "Hello" + "World" + 12345;
  5. System.out.println(str);
  6. // 线程安全的
  7. StringBuffer buffer = new StringBuffer();
  8. buffer.append("Hello");
  9. buffer.append("World");
  10. buffer.append(12345);
  11. System.out.println(buffer);
  12. // 线程不安全
  13. StringBuilder builder = new StringBuilder();
  14. builder.append("Hello");
  15. builder.append("World");
  16. builder.append(12345);
  17. System.out.println(builder);
  18. }
  19. }

字符序列

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. String str = "Hello" + "World" + 12345;
  4. print(str);
  5. StringBuffer buffer = new StringBuffer();
  6. buffer.append("Hello");
  7. buffer.append("World");
  8. buffer.append(12345);
  9. print(buffer);
  10. StringBuilder builder = new StringBuilder();
  11. builder.append("Hello");
  12. builder.append("World");
  13. builder.append(12345);
  14. print(builder);
  15. }
  16. public static void print(CharSequence sequence) {
  17. System.out.println(sequence);
  18. }
  19. }

自动关闭

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. try (Message message = new MyMessage()) {
  4. message.send();
  5. } catch (Exception e) {
  6. e.printStackTrace();
  7. }
  8. }
  9. }
  10. interface Message extends AutoCloseable {
  11. public void send();
  12. }
  13. class MyMessage implements Message {
  14. public void close() throws Exception {
  15. System.out.println("关闭通道");
  16. }
  17. public void send() {
  18. System.out.println("发送消息");
  19. }
  20. }

运行时(Runtime)

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Runtime runtime = Runtime.getRuntime();
  4. System.out.println("CPU核数:" + runtime.availableProcessors());
  5. memory(runtime);
  6. String str = "";
  7. for(int i=0; i<50000; i++) {
  8. str += i + "";
  9. }
  10. System.out.println("字符串长度:" + str.length());
  11. memory(runtime);
  12. runtime.gc();
  13. Thread.sleep(1000);
  14. memory(runtime);
  15. }
  16. private static void memory(Runtime runtime) {
  17. System.out.println("------------------------------");
  18. System.out.println("最大内存:" + toGB(runtime.maxMemory()));
  19. System.out.println("总内存:" + toGB(runtime.totalMemory()));
  20. System.out.println("可以内存:" + toGB(runtime.freeMemory()));
  21. }
  22. private static String toGB(long size) {
  23. return Math.floor(size / 1.0 / 1024 / 1024 / 1024 * 100) / 100 + "GB";
  24. }
  25. }

系统(System)

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. long start = System.currentTimeMillis();
  4. {
  5. String str = "";
  6. for(int i=0; i<1000; i++) {
  7. str += i + "";
  8. }
  9. System.out.println("字符串长度:" + str.length());
  10. }
  11. System.gc();
  12. long end = System.currentTimeMillis();
  13. System.out.println("操作耗时:" + (end-start));
  14. }
  15. }
  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. // 打印所有Propertie的简单方法
  4. System.getProperties().list(System.out);
  5. }
  6. }

清理(Cleaner)

  1. import java.lang.ref.Cleaner;
  2. public class Demo {
  3. public static void main(String[] args) {
  4. try(MemberCleaning memberCleaning = new MemberCleaning()) {
  5. System.out.println(memberCleaning);
  6. }catch(Exception e) {
  7. e.printStackTrace();
  8. }
  9. }
  10. }
  11. class Member implements Runnable {
  12. public Member() {
  13. System.out.println("创建");
  14. }
  15. public void run() {
  16. System.out.println("销毁");
  17. }
  18. }
  19. // Java9以上版本支持
  20. class MemberCleaning implements AutoCloseable {
  21. private Member member;
  22. private Cleaner.Cleanable cleanable;
  23. private static final Cleaner CLEANER = Cleaner.create();
  24. public MemberCleaning() {
  25. this.member = new Member();
  26. this.cleanable = CLEANER.register(this, this.member);
  27. }
  28. public void close() throws Exception {
  29. this.cleanable.clean();
  30. }
  31. }

克隆

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Member member1 = new Member("张三", 18);
  4. Member member2 = member1.clone();
  5. System.out.println(member1);
  6. System.out.println(member2);
  7. }
  8. }
  9. class Member implements Cloneable {
  10. private String name;
  11. private int age;
  12. public Member(String name, int age) {
  13. this.name = name;
  14. this.age = age;
  15. }
  16. public String toString() {
  17. return super.toString() + " [name=" + name + ", age=" + age + "]";
  18. }
  19. protected Member clone() throws CloneNotSupportedException {
  20. return (Member) super.clone();
  21. }
  22. }

数字操作类

数学计算

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. System.out.println(Math.abs(-7));
  4. System.out.println(Math.max(8, 20));
  5. System.out.println(Math.random());
  6. System.out.println(Math.round(3.14159));
  7. System.out.println(myRound(3.14159, 2));
  8. System.out.println(myRound(3.14159, 3));
  9. }
  10. // 自定义保留N位小数的四舍五入
  11. public static double myRound(double num, int scale) {
  12. return Math.round(num * Math.pow(10,scale)) / Math.pow(10,scale);
  13. }
  14. }

随机数

  1. import java.util.Random;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Random random = new Random();
  5. System.out.println(random.nextBoolean());
  6. System.out.println(random.nextDouble());
  7. for(int i=0; i<10; i++) {
  8. System.out.print(random.nextInt(100) + "、");
  9. }
  10. }
  11. }

大数处理

  1. import java.math.BigDecimal;
  2. import java.math.BigInteger;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. BigInteger num1 = new BigInteger("2353464378658920397684376893768957828937529487543897698389376935");
  6. BigInteger num2 = new BigInteger("83957928375247");
  7. System.out.println("加法:" + num1.add(num2));
  8. System.out.println("减法:" + num1.subtract(num2));
  9. System.out.println("乘法:" + num1.multiply(num2));
  10. System.out.println("除法:" + num1.divide(num2));
  11. BigInteger[] result = num1.divideAndRemainder(num2);
  12. System.out.println("商:" + result[0]);
  13. System.out.println("余数:" + result[1]);
  14. BigDecimal num3 = new BigDecimal("3.141596976431634531351035435456465431315465465465465456465465464654654");
  15. BigDecimal num4 = new BigDecimal("654646.321654");
  16. System.out.println(num3.add(num4));
  17. }
  18. }

日期操作

日期类

  1. import java.util.Date;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Date date = new Date();
  5. System.out.println(date.getTime());
  6. System.out.println(new Date());
  7. System.out.println(new Date(System.currentTimeMillis()));
  8. }
  9. }

日期格式化

  1. import java.text.SimpleDateFormat;
  2. import java.util.Date;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Date date = new Date();
  6. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  7. // 日期转字符串
  8. System.out.println(sdf.format(date));
  9. // 字符串转日期
  10. date = sdf.parse("2021-05-15 15:16:41.337");
  11. System.out.println(date);
  12. }
  13. }

开发支持

正则表达式

  1. import java.util.Arrays;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class Demo {
  5. public static void main(String[] args) {
  6. System.out.println("123456".matches("\\d+"));
  7. System.out.println("a".matches("[abc]"));
  8. System.out.println("d".matches("[^abc]"));
  9. System.out.println("F".matches("[a-zA-Z]"));
  10. System.out.println("5".matches("[0-9]"));
  11. System.out.println("3.14159".matches("\\d+(\\.\\d+)?"));
  12. System.out.println("hg2341@jgjh67^hvh^&*(434jhbj^jbsf)*!mbh".replaceAll("\\W", ""));
  13. System.out.println(Arrays.toString("a65876d987987f888g987987s78789".split("\\d+")));
  14. String str = "INSERT INTO user(id,username,password) VALUES (#{id},#{username},#{password})";
  15. String regex = "#\\{\\w+\\}";
  16. Pattern pattern = Pattern.compile(regex);
  17. Matcher matcher = pattern.matcher(str);
  18. while(matcher.find()) {
  19. System.out.println(matcher.group(0));
  20. }
  21. }
  22. }

国际化

i18n.properties

  1. info=Hi
  2. msg=Hi {0} , Welcome to {1}

i18n_en_US.properties

  1. info=Hello
  2. msg=Hello {0} , Welcome to {1}

i18n_zh_CN.properties

  1. info=Ni Hao
  2. msg=Ni Hao {0} , Huan ying lai dao {1}
  1. import java.text.MessageFormat;
  2. import java.util.Locale;
  3. import java.util.ResourceBundle;
  4. public class Demo {
  5. public static void main(String[] args) {
  6. Locale locale = new Locale("zh", "CN");
  7. ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);
  8. System.out.println(bundle.getString("info"));
  9. String str = MessageFormat.format(bundle.getString("msg"), "张三", "三亚");
  10. System.out.println(str);
  11. }
  12. }

UUID

  1. import java.util.UUID;
  2. public class Demo {
  3. public static void main(String[] args) {
  4. System.out.println(UUID.randomUUID().toString());
  5. }
  6. }

Optional

  1. import java.util.Optional;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. System.out.println(getCarInsuranceName1(null));
  5. System.out.println(getCarInsuranceName2(null));
  6. }
  7. public static String getCarInsuranceName1(Person person) {
  8. if(person != null) {
  9. Car car = person.getCar();
  10. if(car != null) {
  11. Insurance insurance = car.getInsurance();
  12. if(insurance != null) {
  13. return insurance.getName();
  14. }
  15. }
  16. }
  17. return "Unknown";
  18. }
  19. public static String getCarInsuranceName2(Person person) {
  20. return Optional.ofNullable(person)
  21. .map(Person::getCar)
  22. .map(Car::getInsurance)
  23. .map(Insurance::getName)
  24. .orElse("Unknown");
  25. }
  26. }
  27. class Person {
  28. private Car car;
  29. public Car getCar() {
  30. return car;
  31. }
  32. }
  33. class Car {
  34. private Insurance insurance;
  35. public Insurance getInsurance() {
  36. return insurance;
  37. }
  38. }
  39. class Insurance {
  40. private String name;
  41. public String getName() {
  42. return name;
  43. }
  44. }

ThreadLocal

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. new Thread(new Runnable() {
  4. public void run() {
  5. Message message = new Message();
  6. message.setInfo("AAAAA");
  7. Channel.setMessage(message);
  8. Channel.send();
  9. }
  10. }, "线程A").start();
  11. new Thread(new Runnable() {
  12. public void run() {
  13. Message message = new Message();
  14. message.setInfo("BBBBB");
  15. Channel.setMessage(message);
  16. Channel.send();
  17. }
  18. }, "线程B").start();
  19. new Thread(new Runnable() {
  20. public void run() {
  21. Message message = new Message();
  22. message.setInfo("CCCCC");
  23. Channel.setMessage(message);
  24. Channel.send();
  25. }
  26. }, "线程C").start();
  27. }
  28. }
  29. class Channel {
  30. private static final ThreadLocal<Message> THREAD_LOCAL = new ThreadLocal<Message>();
  31. private Channel() { }
  32. public static void setMessage(Message message) {
  33. THREAD_LOCAL.set(message);
  34. }
  35. public static void send() {
  36. System.out.println(Thread.currentThread().getName() + "发送消息:" + THREAD_LOCAL.get().getInfo());
  37. }
  38. }
  39. class Message {
  40. private String info;
  41. public String getInfo() {
  42. return info;
  43. }
  44. public void setInfo(String info) {
  45. this.info = info;
  46. }
  47. }

定时调度

  1. import java.util.Timer;
  2. import java.util.TimerTask;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Timer timer = new Timer();
  6. // timer.schedule(new MyTask(), 0);
  7. timer.scheduleAtFixedRate(new MyTask(), 100, 1000);
  8. }
  9. }
  10. class MyTask extends TimerTask {
  11. public void run() {
  12. System.out.println(Thread.currentThread().getName() + "执行了");
  13. }
  14. }

Base64加密和解密

  1. import java.util.Base64;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. String str = "Hello 世界!";
  5. String msg = new String(Base64.getEncoder().encode(str.getBytes()));
  6. System.out.println("加密:" + msg);
  7. String oldStr = new String(Base64.getDecoder().decode(msg.getBytes()));
  8. System.out.println("解密:" + oldStr);
  9. System.out.println("-----------------------------------");
  10. String result1 = encode(str);
  11. String result2 = decode(result1);
  12. System.out.println("自定义加密:" + result1);
  13. System.out.println("自定义解密:" + result2);
  14. }
  15. // 自定义加密
  16. public static String encode(String str) {
  17. str = "盐值123" + str;
  18. byte[] bytes = str.getBytes();
  19. for(int i=0; i<3; i++) {
  20. bytes = Base64.getEncoder().encode(bytes);
  21. }
  22. return new String(bytes);
  23. }
  24. // 自定义解密
  25. public static String decode(String str) {
  26. byte[] bytes = str.getBytes();
  27. for(int i=0; i<3; i++) {
  28. bytes = Base64.getDecoder().decode(bytes);
  29. }
  30. return new String(bytes).replaceFirst("盐值123", "");
  31. }
  32. }

对象排序

  1. import java.util.Arrays;
  2. public class Demo {
  3. public static void main(String[] args) {
  4. Person[] persons = new Person[3];
  5. persons[0] = new Person("张三A", 18);
  6. persons[1] = new Person("张三B", 18);
  7. persons[2] = new Person("张三C", 16);
  8. Arrays.sort(persons);
  9. for (Person person : persons) {
  10. System.out.println(person);
  11. }
  12. }
  13. }
  14. class Person implements Comparable<Person> {
  15. private String name;
  16. private Integer age;
  17. public Person(String name, Integer age) {
  18. super();
  19. this.name = name;
  20. this.age = age;
  21. }
  22. public String toString() {
  23. return "Person [name=" + name + ", age=" + age + "]";
  24. }
  25. public int compareTo(Person person) {
  26. int result = age.compareTo(person.age);
  27. return result==0 ? name.compareTo(person.name) : result;
  28. }
  29. }

案例:生成字符串(A-Z)

  1. public class Demo {
  2. public static void main(String[] args) {
  3. StringBuffer buffer = new StringBuffer();
  4. for(int i='A'; i<='Z'; i++) {
  5. buffer.append((char)i);
  6. }
  7. System.out.println(buffer);
  8. }
  9. }

IO操作

文件操作类

  1. import java.io.File;
  2. import java.util.Date;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. File file = new File("AA/BB/CC/DDD.txt");
  6. if(!file.exists()) {
  7. System.out.println("文件不存在");
  8. File parent = file.getParentFile();
  9. if(!parent.exists()) {
  10. System.out.println("父目录不存在,开始创建父目录:" + parent.mkdirs());
  11. }else {
  12. System.out.println("父目录存在");
  13. }
  14. System.out.println("创建文件:" + file.createNewFile());
  15. }else {
  16. System.out.println("文件已存在");
  17. }
  18. System.out.println("文件绝对路径:" + file.getAbsolutePath());
  19. System.out.println("文件名称:" + file.getName());
  20. System.out.println("文件大小字节数:" + file.length());
  21. System.out.println("文件最后修改时间:" + new Date(file.lastModified()));
  22. System.out.println("文件是否可读:" + file.canRead());
  23. System.out.println("文件是否可写:" + file.canWrite());
  24. System.out.println("是否是文件夹:" + file.isDirectory());
  25. System.out.println("删除文件:" + file.delete());
  26. File aa = file.getParentFile().getParentFile().getParentFile();
  27. System.out.println("列文件夹:");
  28. File[] files = aa.listFiles();
  29. for (File file2 : files) {
  30. System.out.println(file2.getName());
  31. }
  32. }
  33. }

写字节数据到文件

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. File file = new File("text.txt");
  6. try (FileOutputStream out = new FileOutputStream(file)) {
  7. out.write("1 Hello World!!!\r\n".getBytes());
  8. out.write("2 Hello World!!!\r\n".getBytes());
  9. out.write("3 Hello World!!!\r\n".getBytes());
  10. out.flush();
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. System.out.println(file.getAbsolutePath());
  15. }
  16. }

从文件读取字节数据

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.InputStream;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. File file = new File("text.txt");
  7. InputStream in = new FileInputStream(file);
  8. byte[] buf = new byte[1024];
  9. int len = in.read(buf);
  10. in.close();
  11. String str = new String(buf, 0, len);
  12. System.out.println(str);
  13. }
  14. }

写字符数据到文件

  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.Writer;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. File file = new File("text.txt");
  7. Writer writer = new FileWriter(file);
  8. writer.write("AAAAAAA");
  9. writer.write("BBBBBBB");
  10. writer.write("\r\n");
  11. writer.append("CCCCCC");
  12. writer.append("DDDDDD");
  13. writer.flush();
  14. writer.close();
  15. System.out.println(file.getAbsolutePath());
  16. }
  17. }

从文件读取字符数据

  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.Reader;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. File file = new File("text.txt");
  7. Reader reader = new FileReader(file);
  8. char[] cbuf = new char[1024];
  9. int len = reader.read(cbuf);
  10. reader.close();
  11. String str = new String(cbuf, 0, len);
  12. System.out.println(str);
  13. }
  14. }

转换流

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. public class Demo {
  7. public static void main(String[] args) throws Exception {
  8. File file = new File("text.txt");
  9. // 写文件
  10. FileOutputStream out = new FileOutputStream(file);
  11. OutputStreamWriter writer = new OutputStreamWriter(out);
  12. writer.write("AAA\r\n");
  13. writer.write("BBB\r\n");
  14. writer.write("CCC\r\n");
  15. writer.flush();
  16. writer.close();
  17. // 读文件
  18. FileInputStream in = new FileInputStream(file);
  19. InputStreamReader reader = new InputStreamReader(in);
  20. char[] cbuf = new char[1024];
  21. int len = reader.read(cbuf);
  22. reader.close();
  23. String str = new String(cbuf, 0, len);
  24. System.out.println(str);
  25. }
  26. }

文件夹拷贝

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. File folder = new File(System.getenv("JAVA_HOME"));
  7. if(folder.exists() && folder.isDirectory()) {
  8. File dest = new File("复制");
  9. if(!dest.exists()) dest.mkdir();
  10. if(dest.isDirectory()) copyFolder(folder, dest);
  11. }
  12. System.out.println("OK");
  13. }
  14. // 复制文件夹
  15. private static void copyFolder(File from, File to) throws Exception {
  16. File[] files = from.listFiles();
  17. for (File file : files) {
  18. if(file.isDirectory()) {
  19. File fromFile = file;
  20. File toFile = new File(to, fromFile.getName());
  21. toFile.mkdir();
  22. copyFolder(fromFile, toFile);
  23. }else {
  24. File fromFile = file;
  25. File toFile = new File(to, fromFile.getName());
  26. FileInputStream in = new FileInputStream(fromFile);
  27. FileOutputStream out = new FileOutputStream(toFile);
  28. byte[] buf = new byte[2048];
  29. int len = -1;
  30. while((len=in.read(buf)) != -1) {
  31. out.write(buf, 0, len);
  32. }
  33. out.flush();
  34. out.close();
  35. in.close();
  36. System.out.println(toFile.getAbsolutePath());
  37. }
  38. }
  39. }
  40. }

内存流

  1. import java.io.ByteArrayInputStream;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.CharArrayReader;
  4. import java.io.CharArrayWriter;
  5. public class Demo {
  6. public static void main(String[] args) throws Exception {
  7. int data = -1;
  8. String str = "www.baidu.com";
  9. // 字节内存流
  10. ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes());
  11. ByteArrayOutputStream out = new ByteArrayOutputStream();
  12. while((data=in.read()) != -1) {
  13. out.write(Character.toUpperCase(data));
  14. }
  15. System.out.println(out.toString());
  16. out.close();
  17. in.close();
  18. // 字符内存流
  19. CharArrayReader reader = new CharArrayReader(str.toCharArray());
  20. CharArrayWriter writer = new CharArrayWriter();
  21. while((data=reader.read()) != -1) {
  22. writer.write(Character.toUpperCase(data));
  23. }
  24. System.out.println(writer.toString());
  25. writer.close();
  26. reader.close();
  27. }
  28. }

管道流

  1. import java.io.PipedInputStream;
  2. import java.io.PipedOutputStream;
  3. // 字节管道流
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. SendThread sendThread = new SendThread();
  7. ReceiveThread receiveThread = new ReceiveThread();
  8. sendThread.getOutput().connect(receiveThread.getInput());
  9. new Thread(sendThread).start();
  10. new Thread(receiveThread).start();
  11. }
  12. }
  13. class SendThread implements Runnable {
  14. private PipedOutputStream out = new PipedOutputStream();
  15. public void run() {
  16. try {
  17. for(int i=0; i<10; i++) {
  18. String temp = "Hello" + i;
  19. out.write(temp.getBytes());
  20. System.out.println("发送:" + temp);
  21. }
  22. out.close();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. } finally {
  26. System.out.println("发送线程结束");
  27. }
  28. }
  29. public PipedOutputStream getOutput() {
  30. return out;
  31. }
  32. }
  33. class ReceiveThread implements Runnable {
  34. private PipedInputStream in = new PipedInputStream();
  35. public void run() {
  36. try {
  37. int len = -1;
  38. byte[] buf = new byte[6];
  39. while((len=in.read(buf)) != -1) {
  40. Thread.sleep(500);
  41. System.out.println("接收:" + new String(buf, 0, len));
  42. }
  43. in.close();
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. } finally {
  47. System.out.println("接收线程结束");
  48. }
  49. }
  50. public PipedInputStream getInput() {
  51. return in;
  52. }
  53. }
  1. import java.io.PipedReader;
  2. import java.io.PipedWriter;
  3. // 字符管道流
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. SendThread sendThread = new SendThread();
  7. ReceiveThread receiveThread = new ReceiveThread();
  8. sendThread.getWrite().connect(receiveThread.getReader());
  9. new Thread(sendThread).start();
  10. new Thread(receiveThread).start();
  11. }
  12. }
  13. class SendThread implements Runnable {
  14. private PipedWriter writer = new PipedWriter();
  15. public void run() {
  16. try {
  17. for(int i=0; i<10; i++) {
  18. String temp = "Hello" + i;
  19. writer.write(temp);
  20. System.out.println("发送:" + temp);
  21. }
  22. writer.close();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. } finally {
  26. System.out.println("发送线程结束");
  27. }
  28. }
  29. public PipedWriter getWrite() {
  30. return writer;
  31. }
  32. }
  33. class ReceiveThread implements Runnable {
  34. private PipedReader reader = new PipedReader();
  35. public void run() {
  36. try {
  37. int len = -1;
  38. char[] buf = new char[6];
  39. while((len=reader.read(buf)) != -1) {
  40. Thread.sleep(500);
  41. System.out.println("接收:" + new String(buf, 0, len));
  42. }
  43. reader.close();
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. } finally {
  47. System.out.println("接收线程结束");
  48. }
  49. }
  50. public PipedReader getReader() {
  51. return reader;
  52. }
  53. }

随机访问文件

  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.RandomAccessFile;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. File file = new File("test.txt");
  7. // 测试数据准备
  8. FileWriter writer = new FileWriter(file);
  9. writer.write("AAAAA");
  10. writer.write("BBBBB");
  11. writer.write("CCCCC");
  12. writer.write("DDDDD");
  13. writer.close();
  14. // 随机访问文件
  15. RandomAccessFile raf = new RandomAccessFile(file, "rw");
  16. // 跳过15个字节
  17. raf.skipBytes(15);
  18. // 读5个字节
  19. byte[] buf = new byte[5];
  20. int len = raf.read(buf);
  21. System.out.println(new String(buf, 0, len));
  22. // 回退10个字节
  23. raf.seek(10);
  24. // 再读5个字节
  25. len = raf.read(buf);
  26. System.out.println(new String(buf, 0, len));
  27. // 关闭
  28. raf.close();
  29. }
  30. }

缓冲流

  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.FileReader;
  9. import java.io.FileWriter;
  10. public class Demo {
  11. public static void main(String[] args) throws Exception {
  12. File file = new File("test.txt");
  13. // 字节缓冲流
  14. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
  15. out.write("AAAA\r\n".getBytes());
  16. out.write("BBBB\r\n".getBytes());
  17. out.write("CCCC\r\n".getBytes());
  18. out.close();
  19. BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
  20. byte[] buf = new byte[1024];
  21. int len = in.read(buf);
  22. System.out.println(new String(buf, 0, len));
  23. in.close();
  24. // 字符缓冲流
  25. BufferedWriter writer = new BufferedWriter(new FileWriter(file));
  26. writer.write("AAAA\r\n");
  27. writer.write("BBBB\r\n");
  28. writer.write("CCCC\r\n");
  29. writer.close();
  30. BufferedReader reader = new BufferedReader(new FileReader(file));
  31. System.out.println(reader.readLine());
  32. System.out.println(reader.readLine());
  33. System.out.println(reader.readLine());
  34. reader.close();
  35. }
  36. }

输入输出

打印流

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.PrintStream;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. File file = new File("test.txt");
  7. PrintStream stream = new PrintStream(new FileOutputStream(file));
  8. stream.print(true);
  9. stream.print('A');
  10. stream.print("Hello");
  11. stream.printf("姓名:%s,年龄:%d", "张三", 18);
  12. stream.close();
  13. System.out.println("OK");
  14. }
  15. }

System对输入输出的支持

  1. import java.io.InputStream;
  2. public class Demo {
  3. public static void main(String[] args) {
  4. try {
  5. InputStream in = System.in;
  6. System.out.print("请随便输入数据:");
  7. byte[] buf = new byte[10];
  8. int len = in.read(buf);
  9. System.out.println(new String(buf, 0, len));
  10. System.out.println(10/0);
  11. } catch (Exception e) {
  12. System.out.println(e.getMessage());
  13. System.err.println(e.getMessage());
  14. }
  15. }
  16. }

扫描流

  1. import java.io.File;
  2. import java.io.PrintStream;
  3. import java.util.Scanner;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. // 键盘输入
  7. Scanner scanner = new Scanner(System.in);
  8. System.out.print("输入数字:");
  9. long num = scanner.nextLong();
  10. System.out.println("你输入了:" + num);
  11. System.out.print("输入字符串:");
  12. String str = scanner.next();
  13. System.out.println("你输入了:" + str);
  14. scanner.close();
  15. // 写数据
  16. File file = new File("test.txt");
  17. PrintStream stream = new PrintStream(file);
  18. stream.print("AA AAA\r\n");
  19. stream.print("BB BBB\r\n");
  20. stream.print("CC CCC\r\n");
  21. stream.close();
  22. // 读数据
  23. scanner = new Scanner(file);
  24. scanner.useDelimiter("\r\n");
  25. while(scanner.hasNext()) {
  26. System.out.println(scanner.next());
  27. }
  28. scanner.close();
  29. }
  30. }

序列化

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.io.Serializable;
  7. public class Demo {
  8. private static File file = new File("test.txt");
  9. public static void main(String[] args) throws Exception {
  10. Person person = new Person("张三", 18, '男');
  11. saveObject(person);
  12. System.out.println(loadObject());
  13. }
  14. // 序列化
  15. private static void saveObject(Object obj) throws Exception {
  16. ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
  17. out.writeObject(obj);
  18. out.close();
  19. }
  20. // 反序列化
  21. private static Object loadObject() throws Exception {
  22. ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
  23. Object obj = in.readObject();
  24. in.close();
  25. return obj;
  26. }
  27. }
  28. @SuppressWarnings("serial")
  29. class Person implements Serializable {
  30. private String name;
  31. private int age;
  32. // 此属性不会被序列化
  33. private transient char sex;
  34. public Person(String name, int age, char sex) {
  35. super();
  36. this.name = name;
  37. this.age = age;
  38. this.sex = sex;
  39. }
  40. public String toString() {
  41. return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
  42. }
  43. }

反射

Class类对象的3种实例化方式

  1. import java.util.Date;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Class<?> class1 = new Date().getClass();
  5. Class<?> class2 = Date.class;
  6. Class<?> class3 = Class.forName("java.util.Date");
  7. System.out.println(class1);
  8. System.out.println(class2);
  9. System.out.println(class3);
  10. }
  11. }

反射实例化对象

  1. public class Demo {
  2. public static void main(String[] args) throws Exception {
  3. Class<?> cls = Class.forName("Person");
  4. Object object = cls.newInstance();
  5. // JDK1.9以后上面的方法标记为过时,下面是替换的方法
  6. // Object object = cls.getDeclaredConstructor().newInstance();
  7. System.out.println(object);
  8. }
  9. }
  10. class Person {
  11. public Person() {
  12. System.out.println("调用了无参构造方法");
  13. }
  14. public String toString() {
  15. return "调用了toString方法";
  16. }
  17. }

反射与工厂设计模式

  1. // 客户端
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Food food = null;
  5. food = Factory.getInstance("Bread", Bread.class);
  6. food.eat();
  7. food = Factory.getInstance("Rice", Rice.class);
  8. food.eat();
  9. Water water = null;
  10. water = Factory.getInstance("Cola", Cola.class);
  11. water.drink();
  12. water = Factory.getInstance("Sprite", Sprite.class);
  13. water.drink();
  14. }
  15. }
  16. // 食物接口
  17. interface Food {
  18. public void eat();
  19. }
  20. // 面包实现
  21. class Bread implements Food {
  22. public void eat() {
  23. System.out.println("吃面包");
  24. }
  25. }
  26. // 米饭实现
  27. class Rice implements Food {
  28. public void eat() {
  29. System.out.println("吃米饭");
  30. }
  31. }
  32. // 水接口
  33. interface Water {
  34. public void drink();
  35. }
  36. // 可乐实现
  37. class Cola implements Water {
  38. public void drink() {
  39. System.out.println("喝可乐");
  40. }
  41. }
  42. // 雪碧实现
  43. class Sprite implements Water {
  44. public void drink() {
  45. System.out.println("喝雪碧");
  46. }
  47. }
  48. // 工厂
  49. class Factory {
  50. @SuppressWarnings("unchecked")
  51. public static <T> T getInstance(String className, Class<T> clazz) throws Exception {
  52. Class<?> cls = Class.forName(className);
  53. Object object = cls.newInstance();
  54. return (T) object;
  55. }
  56. }

反射与单例懒汉式

  1. public class Demo {
  2. public static void main(String[] args) {
  3. for (int i = 0; i < 3; i++) {
  4. new Thread(() -> {
  5. Massage.getInstance().fun();
  6. }, "线程" + i).start();
  7. }
  8. }
  9. }
  10. // 单例:懒汉式
  11. class Massage {
  12. private static volatile Massage massage;
  13. private Massage() {
  14. System.out.println("调用了构造方法");
  15. }
  16. public static Massage getInstance() {
  17. if (massage == null) {
  18. synchronized (Massage.class) {
  19. if (massage == null) {
  20. massage = new Massage();
  21. }
  22. }
  23. }
  24. return massage;
  25. }
  26. public void fun() {
  27. System.out.println("AAA");
  28. }
  29. }

反射获取类结构信息

  1. public class Demo {
  2. public static void main(String[] args) {
  3. Class<?> cls = String.class;
  4. System.out.println("获取包:" + cls.getPackage());
  5. System.out.println("获取父类:" + cls.getSuperclass());
  6. System.out.println("获取接口:");
  7. Class<?>[] interfaces = cls.getInterfaces();
  8. for (Class<?> clazz : interfaces) {
  9. System.out.println(clazz);
  10. }
  11. }
  12. }

反射调用构造方法

  1. import java.lang.reflect.Constructor;
  2. import java.util.Date;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Class<?> cls = Date.class;
  6. Constructor<?> constructor = cls.getConstructor(long.class);
  7. Object obj = constructor.newInstance(System.currentTimeMillis());
  8. System.out.println(obj);
  9. }
  10. }

反射调用普通方法

  1. import java.lang.reflect.Method;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Class<?> cls = Class.forName("Person");
  5. Object object = cls.newInstance();
  6. Method setMethod = cls.getDeclaredMethod("setName", String.class);
  7. setMethod.invoke(object, "张三");
  8. Method getMethod = cls.getDeclaredMethod("getName");
  9. System.out.println(getMethod.invoke(object));
  10. }
  11. }
  12. class Person {
  13. private String name;
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. }

反射调用成员

  1. import java.lang.reflect.Field;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Class<?> cls = Class.forName("Person");
  5. Object object = cls.newInstance();
  6. // 调用public成员
  7. Field name = cls.getDeclaredField("name");
  8. System.out.println(name.getType());
  9. name.set(object, "张三");
  10. System.out.println(name.get(object));
  11. // 调用private成员
  12. Field age = cls.getDeclaredField("age");
  13. age.setAccessible(true);
  14. System.out.println(age.getType());
  15. age.set(object, 18);
  16. System.out.println(age.get(object));
  17. }
  18. }
  19. class Person {
  20. public String name;
  21. private int age;
  22. }

Unsafe工具类

  1. import java.lang.reflect.Field;
  2. import sun.misc.Unsafe;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Field field = Unsafe.class.getDeclaredField("theUnsafe");
  6. field.setAccessible(true);
  7. Unsafe unsafe = (Unsafe) field.get(null);
  8. // 利用Unsafe类绕过了JVM的管理机制,可以在没有实例化对象的情况下获取Singleton类的实例化对象
  9. Singleton singleton = (Singleton) unsafe.allocateInstance(Singleton.class);
  10. singleton.print();
  11. }
  12. }
  13. class Singleton {
  14. private Singleton() {
  15. System.out.println("执行构造方法");
  16. }
  17. public void print() {
  18. System.out.println("执行print方法");
  19. }
  20. }

反射与简单Java类

  1. import java.lang.reflect.Field;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. // 人
  7. Class<?> personClass = Class.forName("Person");
  8. Object person = personClass.newInstance();
  9. Field nameField = personClass.getDeclaredField("name");
  10. Field ageField = personClass.getDeclaredField("age");
  11. Field computerField = personClass.getDeclaredField("computer");
  12. personClass.getDeclaredMethod(toSetMethodName(nameField.getName()), nameField.getType()).invoke(person, "张三");
  13. personClass.getDeclaredMethod(toSetMethodName(ageField.getName()), ageField.getType()).invoke(person, Integer.parseInt("18"));
  14. // 计算机
  15. Class<?> computerClass = computerField.getType();
  16. Object computer = computerClass.newInstance();
  17. Field brandField = computerClass.getDeclaredField("brand");
  18. Field spaceField = computerClass.getDeclaredField("space");
  19. Field priceField = computerClass.getDeclaredField("price");
  20. Field dateField = computerClass.getDeclaredField("date");
  21. computerClass.getDeclaredMethod(toSetMethodName(brandField.getName()), brandField.getType()).invoke(computer, "华为");
  22. computerClass.getDeclaredMethod(toSetMethodName(spaceField.getName()), spaceField.getType()).invoke(computer, Long.valueOf("5120000000"));
  23. computerClass.getDeclaredMethod(toSetMethodName(priceField.getName()), priceField.getType()).invoke(computer, Double.parseDouble("7599.99"));
  24. computerClass.getDeclaredMethod(toSetMethodName(dateField.getName()), dateField.getType()).invoke(computer, new SimpleDateFormat("yyyy-MM-dd").parse("2021-05-20"));
  25. // 人有计算机
  26. personClass.getDeclaredMethod(toSetMethodName(computerField.getName()), computerClass).invoke(person, computer);
  27. // 打印对象
  28. System.out.println(person);
  29. }
  30. // 根据属性名称拼接setXXX方法名称
  31. public static String toSetMethodName(String key) {
  32. return "set" + Character.toUpperCase(key.charAt(0)) + key.substring(1);
  33. }
  34. }
  35. // 计算机
  36. class Computer {
  37. private String brand;
  38. private Long space;
  39. private double price;
  40. private Date date;
  41. public void setBrand(String brand) {
  42. this.brand = brand;
  43. }
  44. public void setSpace(Long space) {
  45. this.space = space;
  46. }
  47. public void setPrice(double price) {
  48. this.price = price;
  49. }
  50. public void setDate(Date date) {
  51. this.date = date;
  52. }
  53. public String toString() {
  54. return "Computer [brand=" + brand + ", space=" + space + ", price=" + price + ", date=" + date + "]";
  55. }
  56. }
  57. // 人
  58. class Person {
  59. private String name;
  60. private int age;
  61. private Computer computer;
  62. public void setName(String name) {
  63. this.name = name;
  64. }
  65. public void setAge(int age) {
  66. this.age = age;
  67. }
  68. public void setComputer(Computer computer) {
  69. this.computer = computer;
  70. }
  71. public String toString() {
  72. return "Person [name=" + name + ", age=" + age + ", computer=" + computer + "]";
  73. }
  74. }

自定义ClassLoader

  1. public class Message {
  2. public void send(String msg) {
  3. System.out.println("发送消息:" + msg);
  4. }
  5. }
  1. import java.io.ByteArrayOutputStream;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.lang.reflect.Method;
  6. public class Demo {
  7. public static void main(String[] args) throws Exception {
  8. MyClassLoader myClassLoader = new MyClassLoader();
  9. Class<?> clazz = myClassLoader.loadData("E:/Message.class", "Message");
  10. Object object = clazz.newInstance();
  11. Method method = clazz.getDeclaredMethod("send", String.class);
  12. method.invoke(object, "你好");
  13. }
  14. }
  15. class MyClassLoader extends ClassLoader {
  16. public Class<?> loadData(String filePath, String className) throws IOException {
  17. int len = -1;
  18. byte[] buf = new byte[1024];
  19. File file = new File(filePath);
  20. FileInputStream in = new FileInputStream(file);
  21. ByteArrayOutputStream out = new ByteArrayOutputStream();
  22. while((len=in.read(buf)) != -1) {
  23. out.write(buf, 0, len);
  24. }
  25. out.flush();
  26. out.close();
  27. in.close();
  28. byte[] data = out.toByteArray();
  29. return defineClass(className, data, 0, data.length);
  30. }
  31. }

动态代理设计模式

  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Proxy;
  4. // 客户端
  5. public class Demo {
  6. public static void main(String[] args) {
  7. Food food = (Food) new FoodProxy().bind(new Bread());
  8. food.eat();
  9. }
  10. }
  11. // 食物接口
  12. interface Food {
  13. public void eat();
  14. }
  15. // 面包实现
  16. class Bread implements Food {
  17. public void eat() {
  18. System.out.println("吃面包");
  19. }
  20. }
  21. // 食物代理
  22. class FoodProxy implements InvocationHandler {
  23. private Object target;
  24. public Object bind(Object target) {
  25. this.target = target;
  26. return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
  27. }
  28. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  29. System.out.println("吃之前处理");
  30. Object result = method.invoke(target, args);
  31. System.out.println("吃之后处理");
  32. return result;
  33. }
  34. }

CGLib实现代理设计模式

  1. <dependency>
  2. <groupId>cglib</groupId>
  3. <artifactId>cglib</artifactId>
  4. <version>3.3.0</version>
  5. </dependency>
  1. import java.lang.reflect.Method;
  2. import net.sf.cglib.proxy.Enhancer;
  3. import net.sf.cglib.proxy.MethodInterceptor;
  4. import net.sf.cglib.proxy.MethodProxy;
  5. // 客户端
  6. public class Demo {
  7. public static void main(String[] args) {
  8. Bread bread = new Bread();
  9. Enhancer enhancer = new Enhancer();
  10. enhancer.setSuperclass(bread.getClass());
  11. enhancer.setCallback(new BreadProxy(bread));
  12. Bread bread2 = (Bread) enhancer.create();
  13. bread2.eat();
  14. }
  15. }
  16. // 面包
  17. class Bread {
  18. public void eat() {
  19. System.out.println("吃面包");
  20. }
  21. }
  22. // 面包代理
  23. class BreadProxy implements MethodInterceptor {
  24. private Object target;
  25. public BreadProxy(Object target) {
  26. this.target = target;
  27. }
  28. public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
  29. System.out.println("吃之前处理");
  30. Object result = method.invoke(target, args);
  31. System.out.println("吃之后处理");
  32. return result;
  33. }
  34. }

获取Annotation信息

  1. import java.io.Serializable;
  2. import java.lang.annotation.Annotation;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. print(Message.class.getAnnotations());
  6. print(MessageImpl.class.getAnnotations());
  7. print(MessageImpl.class.getDeclaredMethod("send").getAnnotations());
  8. }
  9. public static void print(Annotation[] annotations) {
  10. System.out.println("------------------------");
  11. for (Annotation annotation : annotations) {
  12. System.out.println(annotation);
  13. }
  14. }
  15. }
  16. @FunctionalInterface//RetentionPolicy.RUNTIME
  17. @Deprecated//RetentionPolicy.RUNTIME
  18. interface Message {
  19. public void send();
  20. }
  21. @SuppressWarnings("serial")//RetentionPolicy.SOURCE
  22. class MessageImpl implements Message, Serializable {
  23. @Override//RetentionPolicy.SOURCE
  24. public void send() {
  25. System.out.println("发送消息");
  26. }
  27. }

自定义Annotation

  1. import java.lang.annotation.Retention;
  2. import java.lang.annotation.RetentionPolicy;
  3. import java.lang.reflect.Method;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. Class<?> clazz = Message.class;
  7. Method method = clazz.getMethod("send", String.class);
  8. MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
  9. String msg = annotation.title() + "-" + annotation.url();
  10. method.invoke(clazz.newInstance(), msg);
  11. }
  12. }
  13. @Retention(RetentionPolicy.RUNTIME)
  14. @interface MyAnnotation {
  15. public String title();
  16. public String url() default "www.baidu.com";
  17. }
  18. class Message {
  19. @MyAnnotation(title = "百度")
  20. public void send(String msg) {
  21. System.out.println("发送消息:" + msg);
  22. }
  23. }

代理、工厂、Annotation整合

  1. import java.lang.annotation.Retention;
  2. import java.lang.annotation.RetentionPolicy;
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.Method;
  5. import java.lang.reflect.Proxy;
  6. // 客户端
  7. public class Demo {
  8. public static void main(String[] args) throws Exception {
  9. MessageService messageService = new MessageService();
  10. messageService.send("Hello");
  11. }
  12. }
  13. // 消息接口
  14. interface Message {
  15. public void send(String msg);
  16. }
  17. // 消息实现1
  18. class MessageImpl implements Message {
  19. public void send(String msg) {
  20. System.out.println("发送消息:" + msg);
  21. }
  22. }
  23. // 消息实现2
  24. class NetMessageImpl implements Message {
  25. public void send(String msg) {
  26. System.out.println("网络发送消息:" + msg);
  27. }
  28. }
  29. // 消息代理
  30. class MessageProxy implements InvocationHandler {
  31. private Object target;
  32. public Object bind(Object target) {
  33. this.target = target;
  34. return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
  35. }
  36. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  37. System.out.println("发送前处理");
  38. Object result = method.invoke(target, args);
  39. System.out.println("发送后处理");
  40. return result;
  41. }
  42. }
  43. // 消息工厂
  44. class Factory {
  45. private Factory() { }
  46. @SuppressWarnings("unchecked")
  47. public static <T> T getInstance(Class<?> clazz) throws Exception {
  48. return (T) new MessageProxy().bind(clazz.newInstance());
  49. }
  50. }
  51. // 消息注解
  52. @Retention(RetentionPolicy.RUNTIME)
  53. @interface UseMessage {
  54. public Class<?> clazz();
  55. }
  56. // 消息服务
  57. //@UseMessage(clazz = MessageImpl.class)
  58. @UseMessage(clazz = NetMessageImpl.class)
  59. class MessageService {
  60. private Message message;
  61. public MessageService() throws Exception {
  62. UseMessage annotation = MessageService.class.getAnnotation(UseMessage.class);
  63. message = Factory.getInstance(annotation.clazz());
  64. }
  65. public void send(String msg) {
  66. message.send(msg);
  67. }
  68. }

集合

List

List特点:元素有放入顺序,元素可重复

List新支持

  1. import java.util.List;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. // JDK9
  5. List<String> list = List.of("Hello","World","你好","世界");
  6. System.out.println(list);
  7. }
  8. }

ArrayList

  • ArrayList 是一个可改变大小的数组.当更多的元素加入到ArrayList中时,其大小将会动态地增长.内部的元素可以直接通过get与set方法进行访问,因为ArrayList本质上就是一个数组
  • 默认情况下ArrayList的初始容量非常小,所以如果可以预估数据量的话,分配一个较大的初始值属于最佳实践,这样可以减少调整大小的开销 ```java import java.util.ArrayList; import java.util.List;

public class Demo { public static void main(String[] args) throws Exception { List list = new ArrayList(); list.add(“AAA”); list.add(“AAA”); list.add(“BBB”); list.add(“CCC”); list.add(“DDD”); list.add(null); list.add(null); list.forEach((str)->{ System.out.print(str + “、”); }); System.out.println(); for(int i=0; i<list.size(); i++) { System.out.print(list.get(i) + “、”); } list.clear(); System.out.println(“\n是否为空:” + list.isEmpty());

  1. System.out.println();
  2. List<Person> persons = new ArrayList<Person>();
  3. persons.add(new Person("张三", 18));
  4. persons.add(new Person("李四", 19));
  5. persons.add(new Person("小强", 20));
  6. persons.remove(new Person("小强", 20));
  7. persons.forEach(System.out::println);
  8. }

} class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String toString() { return “Person [name=” + name + “, age=” + age + “]”; } }

  1. <a name="jrHDq"></a>
  2. #### LinkedList
  3. - LinkedList 是一个双链表,在添加和删除元素时具有比ArrayList更好的性能.但在get与set方面弱于ArrayList
  4. - LinkedList 还实现了 Queue 接口,该接口比List提供了更多的方法,包括 offer(),peek(),poll()等
  5. ```java
  6. import java.util.LinkedList;
  7. import java.util.List;
  8. public class Demo {
  9. public static void main(String[] args) throws Exception {
  10. List<String> list = new LinkedList<String>();
  11. list.add("AAA");
  12. list.add("AAA");
  13. list.add("BBB");
  14. list.add("CCC");
  15. list.add("DDD");
  16. list.add(null);
  17. list.add(null);
  18. list.forEach(System.out::println);
  19. }
  20. }

Vector

  • Vector 和ArrayList类似,但属于强同步类。如果你的程序本身是线程安全的(thread-safe,没有在多个线程之间共享同一个集合/对象),那么使用ArrayList是更好的选择
  • Vector和ArrayList在更多元素添加进来时会请求更大的空间。Vector每次请求其大小的双倍空间,而ArrayList每次对size增长50%
  • 序列化存储相同内容的Vector与ArrayList,分别到一个文本文件中去。Vector需要243字节ArrayList需要135字节,是因为ArrayList只保存了非null的数组位置上的数据,而Vector会把null值也拷贝存储 ```java import java.util.List; import java.util.Vector;

public class Demo { public static void main(String[] args) throws Exception { List list = new Vector(); list.add(“AAA”); list.add(“AAA”); list.add(“BBB”); list.add(“CCC”); list.add(“DDD”); list.add(null); list.add(null); list.forEach(System.out::println); } }

  1. <a name="LavZ1"></a>
  2. ### Set
  3. Set特点:元素无放入顺序,元素不可重复
  4. <a name="tiGwG"></a>
  5. #### Set新支持
  6. ```java
  7. import java.util.Set;
  8. public class Demo {
  9. public static void main(String[] args) throws Exception {
  10. // JDK9
  11. Set<String> list = Set.of("Hello","World","你好","世界");
  12. System.out.println(list);
  13. }
  14. }

HashSet

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. public class Demo {
  4. public static void main(String[] args) {
  5. Set<String> set = new HashSet<String>();
  6. set.add("Hello");
  7. set.add("Wrold");
  8. set.add("Wrold");
  9. set.add(null);
  10. set.add(null);
  11. System.out.println(set);
  12. }
  13. }

HashSet重复元素消除

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. public class Demo {
  4. public static void main(String[] args) {
  5. Set<Person> set = new HashSet<Person>();
  6. set.add(new Person("张三", 18));
  7. set.add(new Person("李四", 16));
  8. set.add(new Person("王五", 20));
  9. set.add(new Person("王五", 12));
  10. set.add(new Person("王五", 12));
  11. set.forEach(System.out::println);
  12. }
  13. }
  14. class Person {
  15. private String name;
  16. private int age;
  17. public Person(String name, int age) {
  18. this.name = name;
  19. this.age = age;
  20. }
  21. public int hashCode() {
  22. final int prime = 31;
  23. int result = 1;
  24. result = prime * result + age;
  25. result = prime * result + ((name == null) ? 0 : name.hashCode());
  26. return result;
  27. }
  28. public boolean equals(Object obj) {
  29. if (this == obj)
  30. return true;
  31. if (obj == null)
  32. return false;
  33. if (getClass() != obj.getClass())
  34. return false;
  35. Person other = (Person) obj;
  36. if (age != other.age)
  37. return false;
  38. if (name == null) {
  39. if (other.name != null)
  40. return false;
  41. } else if (!name.equals(other.name))
  42. return false;
  43. return true;
  44. }
  45. public String toString() {
  46. return "Person [name=" + name + ", age=" + age + "]";
  47. }
  48. }

TreeSet

  1. import java.util.Set;
  2. import java.util.TreeSet;
  3. public class Demo {
  4. public static void main(String[] args) {
  5. Set<String> set = new TreeSet<String>();
  6. set.add("D");
  7. set.add("B");
  8. set.add("A");
  9. set.add("C");
  10. set.add("C");
  11. System.out.println(set);
  12. }
  13. }

TreeSet存储自定义对象

  1. import java.util.Set;
  2. import java.util.TreeSet;
  3. public class Demo {
  4. public static void main(String[] args) {
  5. Set<Person> set = new TreeSet<Person>();
  6. set.add(new Person("张三", 18));
  7. set.add(new Person("李四", 16));
  8. set.add(new Person("王五", 20));
  9. set.add(new Person("王五", 12));
  10. set.forEach(System.out::println);
  11. }
  12. }
  13. class Person implements Comparable<Person> {
  14. private String name;
  15. private int age;
  16. public Person(String name, int age) {
  17. this.name = name;
  18. this.age = age;
  19. }
  20. public String toString() {
  21. return "Person [name=" + name + ", age=" + age + "]";
  22. }
  23. public int compareTo(Person person) {
  24. if(person.age == age) {
  25. return person.name.compareTo(name);
  26. }else {
  27. return person.age - age;
  28. }
  29. }
  30. }

集合输出

Iterator

  1. import java.util.HashSet;
  2. import java.util.Iterator;
  3. import java.util.Set;
  4. public class Demo {
  5. public static void main(String[] args) {
  6. Set<String> set = new HashSet<String>();
  7. set.add("AAA");
  8. set.add("BBB");
  9. set.add("CCC");
  10. set.add("DDD");
  11. Iterator<String> iterator = set.iterator();
  12. while(iterator.hasNext()) {
  13. String str = iterator.next();
  14. if(str.equals("CCC")) {
  15. iterator.remove();
  16. }else {
  17. System.out.println(str);
  18. }
  19. }
  20. System.out.println(set);
  21. }
  22. }

ListIterator

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.ListIterator;
  4. public class Demo {
  5. public static void main(String[] args) {
  6. List<String> list = new ArrayList<String>();
  7. list.add("AAA");
  8. list.add("BBB");
  9. list.add("CCC");
  10. list.add("DDD");
  11. ListIterator<String> listIterator = list.listIterator();
  12. while(listIterator.hasNext()) {
  13. System.out.println(listIterator.next());
  14. }
  15. System.out.println();
  16. while(listIterator.hasPrevious()) {
  17. System.out.println(listIterator.previous());
  18. }
  19. }
  20. }

Enumeration

  1. import java.util.Enumeration;
  2. import java.util.Vector;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Vector<String> list = new Vector<String>();
  6. list.add("AAA");
  7. list.add("AAA");
  8. list.add("BBB");
  9. list.add("CCC");
  10. list.add("DDD");
  11. list.add(null);
  12. list.add(null);
  13. Enumeration<String> elements = list.elements();
  14. while(elements.hasMoreElements()) {
  15. System.out.println(elements.nextElement());
  16. }
  17. }
  18. }

foreach

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. List<String> list = new ArrayList<String>();
  6. list.add("AAA");
  7. list.add("AAA");
  8. list.add("BBB");
  9. list.add("CCC");
  10. list.add("DDD");
  11. list.add(null);
  12. list.add(null);
  13. for(String str : list) {
  14. System.out.println(str);
  15. }
  16. }
  17. }

Map

Map新支持

  1. import java.util.Map;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. // JDK9
  5. Map<String,Integer> map = Map.of("a",1,"b",2,"c",3);
  6. System.out.println(map);
  7. }
  8. }

HashMap

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Map<String,Integer> map = new HashMap<String, Integer>();
  6. map.put("one", 1);
  7. System.out.println(map.put("two", 2));
  8. System.out.println(map.put("one", 101));
  9. map.put(null, 0);
  10. map.put("zero", null);
  11. System.out.println(map.get("one"));
  12. System.out.println(map.get(null));
  13. System.out.println(map.get("ten"));
  14. System.out.println(map);
  15. }
  16. }

LinkedHashMap

  1. import java.util.LinkedHashMap;
  2. import java.util.Map;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Map<String,Integer> map = new LinkedHashMap<String, Integer>();
  6. map.put("one", 1);
  7. System.out.println(map.put("two", 2));
  8. System.out.println(map.put("one", 101));
  9. map.put(null, 0);
  10. map.put("zero", null);
  11. System.out.println(map.get("one"));
  12. System.out.println(map.get(null));
  13. System.out.println(map.get("ten"));
  14. System.out.println(map);
  15. }
  16. }

Hashtable

  1. import java.util.Hashtable;
  2. import java.util.Map;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Map<String,Integer> map = new Hashtable<String, Integer>();
  6. map.put("one", 1);
  7. System.out.println(map.put("two", 2));
  8. System.out.println(map.put("one", 101));
  9. System.out.println(map.get("one"));
  10. System.out.println(map.get("ten"));
  11. System.out.println(map);
  12. }
  13. }

Map输出

  1. import java.util.Collection;
  2. import java.util.HashMap;
  3. import java.util.Iterator;
  4. import java.util.Map;
  5. import java.util.Map.Entry;
  6. import java.util.Set;
  7. public class Demo {
  8. public static void main(String[] args) throws Exception {
  9. Map<String,Integer> map = new HashMap<String, Integer>();
  10. map.put("one", 1);
  11. map.put("two", 2);
  12. Set<Entry<String, Integer>> set = map.entrySet();
  13. // 遍历方式1
  14. Iterator<Entry<String, Integer>> iterator = set.iterator();
  15. while(iterator.hasNext()) {
  16. Entry<String, Integer> entry = iterator.next();
  17. System.out.println(entry.getKey() + ":" + entry.getValue());
  18. }
  19. // 遍历方式2
  20. for(Entry<String, Integer> entry : set) {
  21. System.out.println(entry.getKey() + ":" + entry.getValue());
  22. }
  23. // 遍历方式3
  24. Set<String> keySet = map.keySet();
  25. for(String key : keySet) {
  26. System.out.println(key + ":" + map.get(key));
  27. }
  28. // 遍历值
  29. Collection<Integer> values = map.values();
  30. for(Integer value : values) {
  31. System.out.println(value);
  32. }
  33. }
  34. }

Map自定义key

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class Demo {
  4. public static void main(String[] args) throws Exception {
  5. Map<Person,String> map = new HashMap<Person,String>();
  6. map.put(new Person("张三", 18), "张三丰");
  7. System.out.println(map.get(new Person("张三", 18)));
  8. }
  9. }
  10. class Person {
  11. private String name;
  12. private int age;
  13. public Person(String name, int age) {
  14. this.name = name;
  15. this.age = age;
  16. }
  17. public int hashCode() {
  18. final int prime = 31;
  19. int result = 1;
  20. result = prime * result + age;
  21. result = prime * result + ((name == null) ? 0 : name.hashCode());
  22. return result;
  23. }
  24. public boolean equals(Object obj) {
  25. if (this == obj)
  26. return true;
  27. if (obj == null)
  28. return false;
  29. if (getClass() != obj.getClass())
  30. return false;
  31. Person other = (Person) obj;
  32. if (age != other.age)
  33. return false;
  34. if (name == null) {
  35. if (other.name != null)
  36. return false;
  37. } else if (!name.equals(other.name))
  38. return false;
  39. return true;
  40. }
  41. public String toString() {
  42. return "Person [name=" + name + ", age=" + age + "]";
  43. }
  44. }

集合工具

Stack栈

  1. import java.util.Stack;
  2. public class Demo {
  3. public static void main(String[] args) throws Exception {
  4. Stack<String> stack = new Stack<String>();
  5. stack.push("AAAA");
  6. stack.push("BBBB");
  7. stack.push("CCCC");
  8. stack.push("DDDD");
  9. System.out.println(stack.pop());
  10. System.out.println(stack.pop());
  11. System.out.println(stack.pop());
  12. System.out.println(stack.pop());
  13. System.out.println(stack.pop());// 报错
  14. }
  15. }

Queue队列

  1. import java.util.LinkedList;
  2. import java.util.PriorityQueue;
  3. import java.util.Queue;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. Queue<String> queue = new LinkedList<String>();
  7. queue.offer("C");
  8. queue.offer("B");
  9. queue.offer("A");
  10. System.out.println(queue.poll());
  11. System.out.println(queue.poll());
  12. System.out.println(queue.poll());
  13. System.out.println("--------------------");
  14. Queue<String> queue2 = new PriorityQueue<String>();
  15. queue2.offer("C");
  16. queue2.offer("B");
  17. queue2.offer("A");
  18. System.out.println(queue2.poll());
  19. System.out.println(queue2.poll());
  20. System.out.println(queue2.poll());
  21. }
  22. }

Properties

  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.FileWriter;
  4. import java.util.Properties;
  5. public class Demo {
  6. public static void main(String[] args) throws Exception {
  7. File file = new File("test.properties");
  8. Properties prop = new Properties();
  9. prop.setProperty("a", "AAA");
  10. prop.setProperty("b", "Hello World");
  11. prop.setProperty("c", "你好 世界");
  12. prop.store(new FileWriter(file), "Notes 注释");
  13. Properties prop2 = new Properties();
  14. prop2.load(new FileReader(file));
  15. System.out.println(prop2.get("c"));
  16. }
  17. }

Collections

Collection 是一个集合接口,它提供了对集合对象进行基本操作的通用接口方法
Collections 是一个包装类,它包含有各种有关集合操作的静态多态方法

  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4. public class Demo {
  5. public static void main(String[] args) throws Exception {
  6. List<String> list = new ArrayList<String>();
  7. Collections.addAll(list, "BBB", "CCC", "AAA");
  8. System.out.println(list);
  9. Collections.reverse(list);//反转
  10. System.out.println(list);
  11. Collections.sort(list);//排序
  12. System.out.println(list);
  13. System.out.println(Collections.binarySearch(list, "CCC"));//排好序后二分查找
  14. }
  15. }

SynchronizedList和Vector的区别

  • SynchronizedList有很好的扩展和兼容功能。他可以将所有的List的子类转成线程安全的类
  • 使用SynchronizedList的时候,进行遍历时要手动进行同步处理
  • SynchronizedList可以指定锁定的对象 ```java import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Vector;

public class Demo { public static void main(String[] args) throws Exception { Vector list1 = new Vector(); List list2 = Collections.synchronizedList(new ArrayList()); list1.add(“Hello”); list2.add(“World”); System.out.println(list1); System.out.println(list2); } }

  1. <a name="snOsn"></a>
  2. ### Stream数据流
  3. <a name="Ww4x8"></a>
  4. #### Stream基本操作
  5. ```java
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.List;
  9. import java.util.stream.Collectors;
  10. import java.util.stream.Stream;
  11. public class Demo {
  12. public static void main(String[] args) throws Exception {
  13. List<String> list = new ArrayList<String>();
  14. Collections.addAll(list, "Java", "JavaScript", "HTML", "CSS", "jQuery");
  15. Stream<String> stream = list.stream();
  16. List<String> result = stream.filter((ele)->ele.toLowerCase().contains("j")).skip(1).limit(2).collect(Collectors.toList());
  17. System.out.println(result);
  18. }
  19. }

网络编程

C/S模型

  1. import java.io.PrintStream;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.util.Scanner;
  5. public class EchoServer {
  6. public static void main(String[] args) throws Exception {
  7. ServerSocket server = new ServerSocket(9999);
  8. System.out.println("等待客户端连接........");
  9. Socket client = server.accept();
  10. Scanner scanner = new Scanner(client.getInputStream());
  11. scanner.useDelimiter("\r\n");
  12. PrintStream stream = new PrintStream(client.getOutputStream());
  13. boolean flag = true;
  14. while(flag) {
  15. if(scanner.hasNext()) {
  16. String string = scanner.next();
  17. if("byebye".equalsIgnoreCase(string)) {
  18. stream.println("ByeBye....");
  19. flag = false;
  20. }else {
  21. stream.println("[echo]" + string);
  22. }
  23. }
  24. }
  25. scanner.close();
  26. stream.close();
  27. client.close();
  28. server.close();
  29. }
  30. }
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.io.PrintStream;
  4. import java.net.Socket;
  5. import java.util.Scanner;
  6. public class EchoClient {
  7. private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));
  8. public static void main(String[] args) throws Exception {
  9. Socket client = new Socket("localhost", 9999);
  10. Scanner scanner = new Scanner(client.getInputStream());
  11. scanner.useDelimiter("\r\n");
  12. PrintStream stream = new PrintStream(client.getOutputStream());
  13. boolean flag = true;
  14. while(flag) {
  15. String input = getString("请输入要发送的内容:");
  16. stream.println(input);
  17. if(scanner.hasNext()) {
  18. System.out.println(scanner.next());
  19. }
  20. if("byebye".equalsIgnoreCase(input)) {
  21. flag = false;
  22. }
  23. }
  24. scanner.close();
  25. stream.close();
  26. client.close();
  27. }
  28. public static String getString(String prompt) throws Exception {
  29. System.out.print(prompt);
  30. return KEYBOARD_INPUT.readLine();
  31. }
  32. }

BIO模型

  1. import java.io.PrintStream;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.util.Scanner;
  5. public class EchoServer {
  6. private static class ClientThread implements Runnable {
  7. private Socket client = null;
  8. private Scanner scanner = null;
  9. private PrintStream stream = null;
  10. private boolean flag = true;
  11. public ClientThread(Socket client) throws Exception {
  12. this.client = client;
  13. this.scanner = new Scanner(client.getInputStream());
  14. this.scanner.useDelimiter("\r\n");
  15. this.stream = new PrintStream(client.getOutputStream());
  16. }
  17. public void run() {
  18. while(flag) {
  19. if(scanner.hasNext()) {
  20. String string = scanner.next();
  21. if("byebye".equalsIgnoreCase(string)) {
  22. stream.println("ByeBye....");
  23. flag = false;
  24. }else {
  25. stream.println("[echo]" + string);
  26. }
  27. }
  28. }
  29. try {
  30. scanner.close();
  31. stream.close();
  32. client.close();
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. public static void main(String[] args) throws Exception {
  39. ServerSocket server = new ServerSocket(9999);
  40. System.out.println("等待客户端连接........");
  41. boolean flag = true;
  42. while(flag) {
  43. Socket client = server.accept();
  44. new Thread(new ClientThread(client)).start();
  45. }
  46. server.close();
  47. }
  48. }

UDP模型

  1. import java.net.DatagramPacket;
  2. import java.net.DatagramSocket;
  3. public class UDPClient {
  4. public static void main(String[] args) throws Exception {
  5. DatagramSocket client = new DatagramSocket(9999);
  6. byte[] data = new byte[1024];
  7. DatagramPacket packet = new DatagramPacket(data, data.length);
  8. System.out.println("客户端等待接收发送的信息.......");
  9. client.receive(packet);
  10. System.out.println("接收到的信息内容为:" + new String(data, 0, packet.getLength()));
  11. client.close();
  12. }
  13. }
  1. import java.net.DatagramPacket;
  2. import java.net.DatagramSocket;
  3. import java.net.InetAddress;
  4. public class UDPServer {
  5. public static void main(String[] args) throws Exception {
  6. DatagramSocket server = new DatagramSocket(9000);
  7. String str = "Hello World!!!";
  8. DatagramPacket packet = new DatagramPacket(str.getBytes(), 0, str.length(), InetAddress.getByName("localhost"), 9999);
  9. server.send(packet);
  10. System.out.println("消息发送完毕");
  11. server.close();
  12. }
  13. }