异常 体系
Error:代表系统级别的错误(属于严重问题),系统一旦出现问题,sun公司会把这些错误封装成Error对象。Error是给sun公司自己用的,不是给我们程序员用的。因此我们开发人员不用管它。
分类
作用
异常是用来查询bug的关键参考信息
异常可以作为方法内部的一种特殊返回值,以便通知调用者底层的执行情况
处理方式
JVM默认的处理方式
自己处理(捕获异常)
抛出异常
JVM默认处理方式
把异常的名称,异常原因及异常出现的位置等信息输出在了控制台
程序停止执行,下面的代码不会再执行了
1 2 3 4 5 6 7 8 9 10 11 12 13 public class Main { public static void main (String[] args) { System.out.println("Hello World" ); System.out.println(2 /0 ); System.out.println("Hello World" ); System.out.println("Hello World" ); } }
捕获异常
快捷键:ctrl+alt+T
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public class Main { public static void main (String[] args) { int [] arr = {1 , 2 , 3 , 4 , 5 }; try { System.out.println(arr[10 ]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组越界了" ); } System.out.println("看看我执行了吗?" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class Main { public static void main (String[] args) { int [] arr = {1 , 2 , 3 , 4 , 5 }; try { System.out.println(arr[10 ]); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } System.out.println("看看我执行了吗?" ); System.out.println(123 ); System.err.println(123 ); } }
抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class Main { public static void main (String[] args) { int [] arr = {1 , 2 , 3 , 4 , 5 }; int max = 0 ; try { max = getMax(arr); } catch (NullPointerException e) { System.out.println("空指针异常" ); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组索引异常" ); } System.out.println(max); } public static int getMax (int [] arr) { if (arr == null ) { throw new NullPointerException (); } if (arr.length == 0 ) { throw new ArithmeticException (); } int max = arr[0 ]; for (int i = 1 ; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } }
自定义异常
1 2 3 4 5 6 7 8 9 10 package com.itheima;public class AgeOutOfBoundsException extends RuntimeException { public AgeOutOfBoundsException () { } public AgeOutOfBoundsException (String message) { super (message); } }
File
File 对象就表示一个路径,可以是文件的路径、也可以是文件夹的路径
这个路径可以是存在的,也允许是不存在的
构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import java.io.File;public class Main { public static void main (String[] args) { String str = "E:\\code\\Java\\a.txt" ; File f1 = new File (str); System.out.println(f1); String parent = "E:\\code\\Java" ; String child = "a.txt" ; File f2 = new File (parent, child); System.out.println(f2); File f3 = new File (parent + "\\" + child); System.out.println(f3); File parent2 = new File ("E:\\code\\Java" ); String child2 = "a.txt" ; File f4 = new File (parent2, child2); System.out.println(f4); } }
成员方法 判断、获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 import java.io.File;public class Main { public static void main (String[] args) { File f1 = new File ("E:\\code\\Java\\a.txt" ); System.out.println(f1.isDirectory()); System.out.println(f1.isFile()); System.out.println(f1.exists()); File f2 = new File ("E:\\code\\Java\\basic-code" ); System.out.println(f1.isDirectory()); System.out.println(f1.isFile()); System.out.println(f1.exists()); File f3 = new File ("E:\\code\\Java\\b.txt" ); System.out.println(f1.isDirectory()); System.out.println(f1.isFile()); System.out.println(f1.exists()); File f4 = new File ("E:\\code\\Java\\a.txt" ); long len = f4.length(); System.out.println(len); File f5 = new File ("E:\\code\\Java\\basic-code" ); long len2 = f5.length(); System.out.println(len2); File f6 = new File ("E:\\code\\Java\\a.txt" ); String path1 = f6.getAbsolutePath(); System.out.println(path1); File f7 = new File ("E:\\code\\Java\\d.txt" ); String path2 = f7.getPath(); System.out.println(path2); File f8 = new File ("E:\\code\\Java\\a.txt" ); String name1 = f8.getName(); System.out.println(name1); File f9 = new File ("E:\\code\\Java\\a.txt" ); long time = f9.lastModified(); System.out.println(time); } }
创建、删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import java.io.File;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { File f1 = new File ("E:\\code\\Java\\a.txt" ); boolean b1 = f1.createNewFile(); System.out.println(b1); File f2 = new File ("E:\\code\\Java\\aaa" ); boolean b2 = f2.mkdir(); System.out.println(b2); File f3 = new File ("E:\\code\\Java\\bbb" ); boolean b3 = f2.mkdirs(); System.out.println(b3); File f4 = new File ("E:\\code\\Java\\a.txt" ); boolean b4 = f4.delete(); System.out.println(b4); } }
获取并遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.io.File;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { File f = new File ("E:\\code\\Java" ); File[] files = f.listFiles(); for (File file : files) { System.out.println(file); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 import java.io.File;import java.io.FileFilter;import java.io.FilenameFilter;import java.io.IOException;import java.util.Arrays;public class Main { public static void main (String[] args) throws IOException { File[] arr = File.listRoots(); System.out.println(Arrays.toString(arr)); File f1 = new File ("E:\\code\\Java" ); String[] arr2 = f1.list(); for (String s : arr2) { System.out.println(s); } File f2 = new File ("E:\\code\\Python" ); String[] arr3 = f2.list(new FilenameFilter () { @Override public boolean accept (File dir, String name) { File src = new File (dir, name); return src.isFile() && name.endsWith(".py" ); } }); System.out.println(arr3); File f3 = new File ("E:\\code\\Python" ); File[] arr4 = f3.listFiles(); for (File f : arr4) { if (f.isFile() && f.getName().endsWith(".py" )) { System.out.println(f); } } File f4 = new File ("E:\\code\\Python" ); File[] arr5 = f4.listFiles(new FileFilter () { @Override public boolean accept (File pathname) { return pathname.isFile() && pathname.getName().endsWith(".py" ); } }); File[] arr6 = f4.listFiles(new FilenameFilter () { @Override public boolean accept (File dir, String name) { File src = new File (dir, name); return src.isFile() && name.endsWith(".py" ); } }); System.out.println(Arrays.toString(arr5)); } }
IO流 用于读写文件中的数据(可以读写文件,或网络中的数据…)
体系
字节流
FileOutputStream 操作本地文件的字节输出流,可以把程序中的数据写到本地文件中。
创建字节输出流对象
写数据
释放资源
构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import java.io.FileOutputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileOutputStream fos = new FileOutputStream ("a.txt" ); fos.write(97 ); fos.close(); } }
API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import java.io.FileOutputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileOutputStream fos = new FileOutputStream ("a.txt" ); byte [] bytes = {97 , 98 , 99 , 100 , 101 }; fos.write(bytes, 1 , 2 ); fos.close(); } }
换行和续写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import java.io.FileOutputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileOutputStream fos = new FileOutputStream ("a.txt" , true ); String str = "I love CS" ; byte [] bytes1 = str.getBytes(); fos.write(bytes1); String wrap = "\r\n" ; byte [] bytes2 = wrap.getBytes(); fos.write(bytes2); String str2 = "520" ; byte [] bytes3 = str2.getBytes(); fos.write(bytes3); fos.close(); } }
操作本地文件的字节输入流,可以把本地文件中的数据读取到程序中来
创建字节输入流对象
读数据
释放资源
构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.io.FileInputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileInputStream fis = new FileInputStream ("a.txt" ); int b1 = fis.read(); System.out.println((char )b1); int b2 = fis.read(); System.out.println((char )b2); int b3 = fis.read(); System.out.println(b3); fis.close(); } }
API
循环读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.io.FileInputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileInputStream fis = new FileInputStream ("a.txt" ); int b; while ((b = fis.read()) != -1 ) { System.out.print((char ) b); } fis.close(); } }
文件拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { long start = System.currentTimeMillis(); FileInputStream fis = new FileInputStream ("a.txt" ); FileOutputStream fos = new FileOutputStream ("b.txt" ); int len; byte [] bytes = new byte [1024 * 1024 * 5 ]; while ((len = fis.read(bytes)) != -1 ) { fos.write(bytes, 0 , len); } fos.close(); fis.close(); long end = System.currentTimeMillis(); System.out.println(end - start); } }
异常处理 注:后续框架Spring统一用抛出异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class Main { public static void main (String[] args) throws FileNotFoundException { FileInputStream fis = new FileInputStream ("a.txt" ); FileOutputStream fos = new FileOutputStream ("b.txt" ); try (fis; fos) { int len; byte [] bytes = new byte [1024 * 1024 * 5 ]; while ((len = fis.read(bytes)) != -1 ) { fos.write(bytes, 0 , len); } } catch (IOException e) { e.printStackTrace(); } } }
字符集
ASCII
GBK
Unicode
乱码原因:
读取数据时未读完整个汉字
编码和解码方式不统一
避免乱码:
不要用字节流读取文本文件
编码解码时使用同一个码表,同一个编码方式
编码和解码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import java.io.UnsupportedEncodingException;import java.util.Arrays;public class Main { public static void main (String[] args) throws UnsupportedEncodingException { String str = "ai你哦" ; byte [] bytes1 = str.getBytes(); System.out.println(Arrays.toString(bytes1)); byte [] bytes2 = str.getBytes("GBK" ); System.out.println(Arrays.toString(bytes2)); String str2 = new String (bytes1); System.out.println(str2); String str3 = new String (bytes1, "GBK" ); System.out.println(str3); } }
字符流
FileReader
构造方法
API
释放资源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import java.io.FileReader;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileReader fr = new FileReader ("a.txt" ); int ch; while ((ch = fr.read()) != -1 ) { System.out.println((char ) ch); } fr.close(); } }
FileWriter
构造方法
API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import java.io.FileWriter;import java.io.IOException;public class Main { public static void main (String[] args) throws IOException { FileWriter fw = new FileWriter ("a.txt" , true ); char [] chars = {'a' , 'b' , 'c' , '我' }; fw.write(chars); fw.close(); } }
文件拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import java.io.*;public class Main { public static void main (String[] args) throws IOException { File src = new File ("oop-polymorphism\\src" ); File dst = new File ("dst" ); copydir(src, dst); } private static void copydir (File src, File dst) throws IOException { dst.mkdirs(); File[] files = src.listFiles(); for (File file : files) { if (file.isFile()) { FileInputStream fis = new FileInputStream (file); FileOutputStream fos = new FileOutputStream (new File (dst, file.getName())); byte [] bytes = new byte [1024 ]; int len; while ((len = fis.read(bytes)) != -1 ) { fos.write(bytes, 0 , len); } fos.close(); fis.close(); } else { copydir(file, new File (dst, file.getName())); } } } }
字节流和字符流的使用场景
字节流:拷贝任意类型的文件
字符流:
读取纯文本文件中的数据
往纯文本文件中写出数据
缓冲流
字节缓冲流
构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import java.io.*;public class Main { public static void main (String[] args) throws IOException { BufferedInputStream bis = new BufferedInputStream (new FileInputStream ("a.txt" )); BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream ("b.txt" )); int len; byte [] bytes = new byte [1024 ]; while ((len = bis.read(bytes)) != -1 ) { bos.write(bytes, 0 , len); } bos.close(); bis.close(); } }
字符缓冲流
构造方法
API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import java.io.*;public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader (new FileReader ("a.txt" )); String line; while ((line = br.readLine()) != null ) { System.out.println(line); } br.close(); BufferedWriter bw = new BufferedWriter (new FileWriter ("b.txt" )); bw.write("ha" ); bw.newLine(); bw.write("la" ); bw.newLine(); bw.close(); } }
转换流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 import java.io.*;import java.nio.charset.Charset;public class Main { public static void main (String[] args) throws IOException { FileReader fr = new FileReader ("a.txt" , Charset.forName("GBK" )); int ch; while ((ch = fr.read()) != -1 ) { System.out.print((char ) ch); } fr.close(); FileWriter fw = new FileWriter ("b.txt" , Charset.forName("GBK" )); fw.write("Hello World" ); fw.close(); FileReader fr2 = new FileReader ("b.txt" , Charset.forName("GBK" )); FileWriter fw2 = new FileWriter ("c.txt" , Charset.forName("UTF-8" )); int b; while ((b = fr2.read()) != -1 ) { fw2.write(b); } fr2.close(); fw2.close(); } }
序列化流
方法
序列化流的细节
使用对象输出流将对象保存到文件时会出现NotSerializableException异常
解决方案:
需要让Javabean类实现Serializable接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.io.Serializable;public class Main { public static void main (String[] args) throws IOException { Student stu = new Student ("ZhangSan" , 18 ); ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("a.txt" )); oos.writeObject(stu); oos.close(); } } class Student implements Serializable { private String name; private int age; public Student () { } public Student (String name, int age) { this .name = name; this .age = age; } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public String toString () { return "Student{name = " + name + ", age = " + age + "}" ; } }
反序列化流
API
细节
打印流
特点
字节打印流
构造方法
API
字符打印流
构造方法
API
解压缩流
解压缩
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import java.io.*;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;public class Main { public static void main (String[] args) throws IOException, ClassNotFoundException { File src = new File ("a.zip" ); File dest = new File ("" ); unzip(src, dest); } public static void unzip (File src, File dest) throws IOException { ZipInputStream zip = new ZipInputStream (new FileInputStream (src)); ZipEntry entry; while ((entry = zip.getNextEntry()) != null ) { System.out.println(entry.getName()); if (entry.isDirectory()) { File file = new File (dest, entry.getName()); file.mkdirs(); } else { FileOutputStream fos = new FileOutputStream (new File (dest, entry.getName())); int b; while ((b = zip.read()) != -1 ) { fos.write(b); } fos.close(); zip.closeEntry(); } } zip.close(); } }
压缩流
压缩
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 public class ZipStreamDemo3 { public static void main (String[] args) throws IOException { File src = new File ("D:\\aaa" ); File destParent = src.getParentFile(); File dest = new File (destParent,src.getName() + ".zip" ); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (dest)); toZip(src,zos,src.getName()); zos.close(); } public static void toZip (File src,ZipOutputStream zos,String name) throws IOException { File[] files = src.listFiles(); for (File file : files) { if (file.isFile()){ ZipEntry entry = new ZipEntry (name + "\\" + file.getName()); zos.putNextEntry(entry); FileInputStream fis = new FileInputStream (file); int b; while ((b = fis.read()) != -1 ){ zos.write(b); } fis.close(); zos.closeEntry(); }else { toZip(file,zos,name + "\\" + file.getName()); } } } }
Commons
Commons是apache开源基金组织提供的工具包,里面有很多帮助我们提高开发效率的API
使用方式:
新建lib文件夹
把第三方jar包粘贴到文件夹中
右键点击add as a library
API
多线程
并发和并行:
并发:在同一时刻,有多个指令在单个CPU上交替执行
并行:在同一时刻,有多个指令在多个CPU上同时执行
实现方式
继承Thread类的方式进行实现
自己定义一个类继承Thread
重写run方法
创建子类的对象,并启动线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class MyThread extends Thread { @Override public void run () { for (int i=0 ; i<100 ; i++) { System.out.println(i); } } } public class Main { public static void main (String[] args) { MyThread my1 = new MyThread (); MyThread my2 = new MyThread (); my1.start(); my2.start(); } }
实现Runnable接口的方式进行实现
自己定义一个类实现Runnable接口
重写里面的run方法
创建自己的类的对象
创建一个Thread类的对象,并开启线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class MyRunnable implements Runnable { @Override public void run () { for (int i=0 ; i<100 ; i++) { System.out.println(Thread.currentThread().getName()+":" +i); } } } public class MyRunnableDemo { public static void main (String[] args) { MyRunnable my = new MyRunnable (); Thread t1 = new Thread (my,"坦克" ); Thread t2 = new Thread (my,"飞机" ); t1.start(); t2.start(); } }
利用Callable接口和Future接口方式实现
创建一个MyCallable实现Callable接口
重写call(含有返回值,表示多线程运行的结果)
创建MyCallable对象(表示多线程要执行的任务)
创建FutureTask对象(作用管理多线程运行的结果)
创建Thread类的对象,并启动(表示线程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class MyCallable implements Callable <String> { @Override public String call () throws Exception { for (int i = 0 ; i < 100 ; i++) { System.out.println("跟女孩表白" + i); } return "答应" ; } } public class Demo { public static void main (String[] args) throws ExecutionException, InterruptedException { MyCallable mc = new MyCallable (); FutureTask<String> ft = new FutureTask <>(mc); Thread t1 = new Thread (ft); String s = ft.get(); t1.start(); String s = ft.get(); System.out.println(s); } }
生命周期
常用方法
线程同步
同步代码块
特点:
锁默认打开,有一个线程进去了,锁自动关闭
里面的代码全部执行完毕,线程出来,锁自动打开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public class SellTicket implements Runnable { int tickets = 100 ; private Object obj = new Object (); @Override public void run () { while (true ) { synchronized (obj) { if (tickets > 0 ) { try { Thread.sleep(100 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票" ); tickets--; } } } } } public class SellTicketDemo { public static void main (String[] args) { SellTicket st = new SellTicket (); Thread t1 = new Thread (st, "窗口1" ); Thread t2 = new Thread (st, "窗口2" ); Thread t3 = new Thread (st, "窗口3" ); t1.start(); t2.start(); t3.start(); } }
同步方法
在原来的基础上 ctrl + alt + M
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 public class MyRunnable implements Runnable { int ticket = 0 ; @Override public void run () { while (true ) { if (method()) break ; } } private synchronized boolean method () { if (ticket == 100 ) { return true ; } else { try { Thread.sleep(100 ); } catch (InterruptedException e) { throw new RuntimeException (e); } ticket++; System.out.println(Thread.currentThread().getName() + ": " + ticket); } return false ; } } public class Main { public static void main (String[] args) { MyRunnable mr = new MyRunnable (); Thread t1 = new Thread (mr); Thread t2 = new Thread (mr); Thread t3 = new Thread (mr); t1.setName("Window 1" ); t2.setName("Window 2" ); t3.setName("Window 3" ); t1.start(); t2.start(); t3.start(); } }
锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 import java.util.concurrent.locks.ReentrantLock; public class Ticket implements Runnable { private int ticket = 100 ; private Object obj = new Object (); private ReentrantLock lock = new ReentrantLock (); @Override public void run () { while (true ) { try { lock.lock(); if (ticket <= 0 ) { break ; } else { Thread.sleep(100 ); ticket--; System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticket + "张票" ); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } } public class Demo { public static void main (String[] args) { Ticket ticket = new Ticket (); Thread t1 = new Thread (ticket); Thread t2 = new Thread (ticket); Thread t3 = new Thread (ticket); t1.setName("窗口一" ); t2.setName("窗口二" ); t3.setName("窗口三" ); t1.start(); t2.start(); t3.start(); } }
死锁 写代码不要让多个锁嵌套起来
生产者 消费者 等待唤醒机制
API
等待唤醒机制(基本形式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 public class Desk { public static int foodFlag = 0 ; public static int count = 10 ; public static Object lock = new Object (); } public class Cook extends Thread { @Override public void run () { while (true ) { synchronized (Desk.lock) { if (Desk.count == 0 ) { break ; } else { if (Desk.foodFlag == 1 ) { try { Desk.lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println("厨师做了一碗面条" ); Desk.foodFlag = 1 ; Desk.lock.notifyAll(); } } } } } } public class Foodie extends Thread { @Override public void run () { while (true ) { synchronized (Desk.lock) { if (Desk.count == 0 ) { break ; } else { if (Desk.foodFlag == 0 ) { try { Desk.lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { Desk.count--; System.out.println("吃货在吃面条,还能再吃" + Desk.count + "碗!!!" ); Desk.lock.notifyAll(); Desk.foodFlag = 0 ; } } } } } } public class Main { public static void main (String[] args) { Cook c = new Cook (); Foodie f = new Foodie (); c.setName("厨师" ); f.setName("吃货" ); c.start(); f.start(); } }
阻塞队列(形式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 public class Cooker extends Thread { private ArrayBlockingQueue<String> bd; public Cooker (ArrayBlockingQueue<String> bd) { this .bd = bd; } @Override public void run () { while (true ) { try { bd.put("汉堡包" ); System.out.println("厨师放入一个汉堡包" ); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Foodie extends Thread { private ArrayBlockingQueue<String> bd; public Foodie (ArrayBlockingQueue<String> bd) { this .bd = bd; } @Override public void run () { while (true ) { try { String take = bd.take(); System.out.println("吃货将" + take + "拿出来吃了" ); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Demo { public static void main (String[] args) { ArrayBlockingQueue<String> bd = new ArrayBlockingQueue <>(1 ); Foodie f = new Foodie (bd); Cooker c = new Cooker (bd); f.start(); c.start(); } }
线程的6个状态
线程池
API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class MyRunnable implements Runnable { @Override public void run () { for (int i = 0 ; i < 100 ; i++) { System.out.println(Thread.currentThread().getName() + "---" + i); } } } public class Main { public static void main (String[] args) { ExecutorService pool1 = Executors.newFixedThreadPool(5 ); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.shutdown(); } }
自定义线程池
拒接策略
自定义线程池 ThreadPoolExecutor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.itheima.mythreadpool;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class MyThreadPoolDemo3 { public static void main (String[] args) { ThreadPoolExecutor pool = new ThreadPoolExecutor ( 2 , 5 , 2 , TimeUnit.SECONDS, new ArrayBlockingQueue <>(10 ), Executors.defaultThreadFactory(), new ThreadPoolExecutor .AbortPolicy() ); pool.submit(new MyRunnable ()); pool.submit(new MyRunnable ()); pool.shutdown(); } }
线程大小
网络编程
三要素
IP:设备在网络中的地址,是唯一的标识
端口:应用程序在设备中唯一的标识
协议:数据在网络中传输的规则,常见的协议有UDP、TCP、http、https、ftp
IP
InetAddress
API
方法名
说明
static InetAddress getByName(String host)
确定主机名称的IP地址。主机名称可以是机器名称,也可以是IP地址
String getHostName()
获取此IP地址的主机名
String getHostAddress()
返回文本显示中的IP地址字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import java.net.InetAddress;import java.net.UnknownHostException;public class Main { public static void main (String[] args) throws UnknownHostException { InetAddress address = InetAddress.getByName("LAPTOP-P1UKKCPI" ); System.out.println(address); String name = address.getHostName(); System.out.println(name); String ip = address.getHostAddress(); System.out.println(ip); } }
端口
协议
UDP
三种通信方式
发送数据(单播)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class SendDemo { public static void main (String[] args) throws IOException { DatagramSocket ds = new DatagramSocket (); String str = "hello,udp,我来了" byte [] bytes = str.getBytes(); InetAddress address = InetAddress.getByName("127.0.0.1" ); int port = 10086 ; DatagramPacket dp = new DatagramPacket (bytes,bytes.length,address,port); ds.send(dp); ds.close(); } }
接受数据(单播)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class ReceiveDemo { public static void main (String[] args) throws IOException { DatagramSocket ds = new DatagramSocket (10086 ); byte [] bytes = new byte [1024 ]; DatagramPacket dp = new DatagramPacket (bytes, bytes.length); ds.receive(dp); byte [] data = dp.getData(); int len = dp.getLength(); InetAddress address = dp.getAddress(); int port = dp.getPort(); System.out.println("接收到数据" + new Strin (data, 0 , len)); System.out.println("该数据是从" + address + "这台电脑中的" + port + "这个端口中发出的" ); ds.close() } }
组播
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 public class ClinetDemo { public static void main (String[] args) throws IOException { MulticastSocket ms = new MulticastSocket (); String s = "hello 组播" ; byte [] bytes = s.getBytes(); InetAddress address = InetAddress.getByName("224.0.1.0" ); int port = 10000 ; DatagramPacket dp = new DatagramPacket (bytes,bytes.length,address,port); ms.send(dp); ms.close(); } } public class ServerDemo { public static void main (String[] args) throws IOException { MulticastSocket ms = new MulticastSocket (10000 ); InetAddress address = InerAddress.getByName("224.0.1.0" ); ms.joinGroup(address); byte [] bytes = new byte [1024 ]; DatagramPacket dp = new DatagramPacket (bytes, bytes.length); ms.receive(dp); byte [] data = dp.getData(); int len = dp.getLength(); String ip = dp.getAddress().getHostAddress(); String name = dp.getAddress().getHostName(); System.out.println("ip为:" + ip + ",主机名为:" + name + "的人,发送了数据:" + new String (data, 0 , len))); ms.close(); } }
广播
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class ClientDemo { public static void main (String[] args) throws IOException { DatagramSocket ds = new DatagramSocket (); String s = "广播 hello" ; byte [] bytes = s.getBytes(); InetAddress address = InetAddress.getByName("255.255.255.255" ); int port = 10000 ; DatagramPacket dp = new DatagramPacket (bytes,bytes.length,address,port); ds.send(dp); ds.close(); } } public class ServerDemo { public static void main (String[] args) throws IOException { DatagramSocket ds = new DatagramSocket (10000 ); DatagramPacket dp = new DatagramPacket (new byte [1024 ],1024 ); ds.receive(dp); byte [] data = dp.getData(); int length = dp.getLength(); System.out.println(new String (data,0 ,length)); ds.close(); } }
TCP
发送数据(英文)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Client { public static void main (String[] args) throws IOException { Socket socket = new Socket ("127.0.0.1" ,10000 ); OutputStream os = socket.getOutputStream(); os.write("aaa" .getBytes()); os.close(); socket.close(); } }
接收数据(英文)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Server { public static void main (String[] args) throws IOException { ServerSocket ss = new ServerSocket (10000 ); Socket socket = ss.accept(); InputStream is = socket.getInputStream(); int b; while ((b = is.read()) != -1 ){ System.out.println((char ) b); } socket.close(); ss.close(); } }
发送数据(中文)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Client { public static void main (String[] args) throws IOException { Socket socket = new Socket ("127.0.0.1" ,10000 ); OutputStream os = socket.getOutputStream(); os.write("你好你好" .getBytes()); os.close(); socket.close(); } }
接收数据(中文)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class Server { public static void main (String[] args) throws IOException { ServerSocket ss = new ServerSocket (10000 ); Socket socket = ss.accept(); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader (is); BufferedReader br = new BufferedReader (isr); int b; while ((b = br.read()) != -1 ){ System.out.print((char ) b); } socket.close(); ss.close(); } }
细节
三次握手
四次挥手
反射
获取 class 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Class clazz1 = Class.forName("com.itheima.reflectdemo.Student" );Class clazz2 = Student.class;System.out.println(clazz1 == clazz2); Student s = new Student ();Class clazz3 = s.getClass();System.out.println(clazz1 == clazz2); System.out.println(clazz2 == clazz3);
获取构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Parameter;public class Main { public static void main (String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { Class clazz = Class.forName("Student" ); Constructor[] cons = clazz.getConstructors(); for (Constructor con : cons) { System.out.println(con); } Constructor[] con1 = clazz.getDeclaredConstructors(); for (Constructor con : con1) { System.out.println(con); } Constructor con2 = clazz.getDeclaredConstructor(); System.out.println(con2); Constructor con3 = clazz.getDeclaredConstructor(String.class); System.out.println(con3); Constructor con5 = clazz.getDeclaredConstructor(String.class, int .class); System.out.println(con5); int modifiers = clazz.getModifiers(); System.out.println(modifiers); Parameter[] parameters = con5.getParameters(); for (Parameter param : parameters) { System.out.println(param); } con5.setAccessible(true ); Student stu = (Student) con5.newInstance("ZhangSan" , 23 ); System.out.println(stu); } }
获取成员变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 public class ReflectDemo4 { public static void main (String[] args) throws ClassNotFoundException, NoSuchFieldException { Class clazz = Class.forName("com.itheima.reflectdemo.Student" ); Field[] fields1 = clazz.getFields(); for (Field field : fields1) { System.out.println(field); } System.out.println("===============================" ); Field[] fields2 = clazz.getDeclaredFields(); for (Field field : fields2) { System.out.println(field); } System.out.println("===============================" ); Field field4 = clazz.getField("gender" ); System.out.println(field4); System.out.println("===============================" ); Field name = clazz.getDeclaredField("name" ); System.out.println(name); int modifiers = name.getModifiers(); System.out.println(modifiers); String n = name.getName(); System.out.println(n); Class<?> type = name.getType(); System.out.println(type); Student s = new Student ("ZhangSan" , 23 , "男" ); name.setAccessible(true ); String value = (String) name.get(s); System.out.println(value); name.set(s, "LiSi" ); System.out.println(s); } } public class Student { private String name; private int age; public String gender; public String address; public Student () { } public Student (String name, int age, String address) { this .name = name; this .age = age; this .address = address; } public Student (String name, int age, String gender, String address) { this .name = name; this .age = age; this .gender = gender; this .address = address; } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public String getGender () { return gender; } public void setGender (String gender) { this .gender = gender; } public String getAddress () { return address; } public void setAddress (String address) { this .address = address; } public String toString () { return "Student{name = " + name + ", age = " + age + ", gender = " + gender + ", address = " + address + "}" ; } }
调用成员方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public class ReflectDemo6 { public static void main (String[] args) throws ClassNotFoundException, NoSuchMethodException { Class<?> clazz = Class.forName("com.itheima.reflectdemo.Student" ); Method[] methods1 = clazz.getMethods(); for (Method method : methods1) { System.out.println(method); } System.out.println("===========================" ); Method[] methods2 = clazz.getDeclaredMethods(); for (Method method : methods2) { System.out.println(method); } System.out.println("===========================" ); Method method3 = clazz.getMethod("sleep" ); System.out.println(method3); Method method4 = clazz.getMethod("eat" ,String.class); System.out.println(method4); Method method5 = clazz.getDeclaredMethod("playGame" ); System.out.println(method5); } }
作用
获取一个类里面所有的信息,获取后,再执行其他的业务逻辑
结合配置文件,动态的创建对象并调用方法
动态代理
代码实现
1 2 3 4 5 6 7 public interface Star { public abstract String sing (String name) ; public abstract void dance () ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 public class BigStar implements Star { private String name; public BigStar () { } public BigStar (String name) { this .name = name; } @Override public String sing (String name) { System.out.println(this .name + "正在唱" + name); return "谢谢" ; } @Override public void dance () { System.out.println(this .name + "正在跳舞" ); } public String getName () { return name; } public void setName (String name) { this .name = name; } public String toString () { return "BigStar{name = " + name + "}" ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 public class ProxyUtil { public static Star createProxy (BigStar bigStar) { Star star = (Star) Proxy.newProxyInstance( ProxyUtil.class.getClassLoader(), new Class []{Star.class}, new InvocationHandler () { @Override public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { if ("sing" .equals(method.getName())){ System.out.println("准备话筒,收钱" ); }else if ("dance" .equals(method.getName())){ System.out.println("准备场地,收钱" ); } return method.invoke(bigStar,args); } } ); return star; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Test { public static void main (String[] args) { BigStar bigStar = new BigStar ("鸡哥" ); Star proxy = ProxyUtil.createProxy(bigStar); String result = proxy.sing("只因你太美" ); System.out.println(result); } }