1 异常 Exception
1.1 Demo
问题
package com.xhh05_exception;
public class Exception_01 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
int ans = num1 / num2;
System.out.println(ans);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.xhh05_exception.Exception_01.main(Exception_01.java:7)
Process finished with exit code 1
解决(异常处理机制)
package com.xhh05_exception;
public class Exception_01 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
try {
int ans = num1 / num2;
System.out.println(ans);
}catch (Exception e){
// 出现异常执行这里,可以继续执行
// e.printStackTrace();
System.out.println("msg:" + e.getMessage());
}
System.out.println("System xhh End ..");
}
}
msg:/ by zero
System xhh End ..
Process finished with exit code 0
1.2 异常介绍
- Error(错误:内存溢出、资源耗尽)
- Exception(空指针访问、网络中断;【编译时异常】和【运行时异常】)
1.3 异常处理方式
- try-catch-finally
- throws
try {
// 可能发生异常的代码
}catch (Exception e){
// 出现异常执行这里,可以继续执行
}finally {
// 肯定会执行的代码
// 释放资源 连接· ···
}
// 默认为throws
// 抛出异常(可以写父类 可以写多个异常抛出)
public void throwFunc() throws Exception{
}
1.4 自定义异常
要求年龄在18-35岁之间
package com.xhh05_exception;
import java.util.Scanner;
public class CustomExpection_ {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
// 18-25
if(num < 18 || num > 25){
throw new AgeExcepthon("need age 18-25 ...");
}
}
}
// 自定义异常
class AgeExcepthon extends RuntimeException{
public AgeExcepthon(String msg){
super(msg);
}
}
Exception in thread "main" com.xhh05_exception.AgeExcepthon: need age 18-25 ...
at com.xhh05_exception.CustomExpection_.main(CustomExpection_.java:11)
2 包装类
- String
- StringBuffer
- StringBuilder
- Math
- Date、Calendar、LocalDate…
- System
- Arrays
- BigInteger
2.1 简介 Wrapper
2.2 装箱和拆箱
装箱(基本类型----到----包装类)
// 装箱(基本类型 ---->包装类)
// jdk5 之前
// 手动装箱
int n1 = 999;
Integer integer1 = new Integer(n1);
Integer integer2 = Integer.valueOf(n1);
// 手动拆箱
int nn1 = integer1.intValue();
// jdk5 之后
// 自动
int n2 = 789;
Integer integer3 = n2; // 底层 Integer.valueOf(n2)
int nn2 = integer3; // 底层 integer3.intValue();
2.3 包装类型转换
// 包装类 -> String
Integer num1 = 999;
// [1]
String s1 = num1.toString();
// [2]
String s2 = "" + num1;
// [3]
String s3 = String.valueOf(num1);
// String -> 包装类
String str = "666";
// [1]
Integer num2 = Integer.parseInt(str);
// [2]
Integer num3 = new Integer(str);
3 常用类
3.1 String
字符串常量 Unicode
String(String original);
String(char value[]);
String(char value[], int offset, int count);
String(int[] codePoints, int offset, int count);
String(byte bytes[]);
String(byte bytes[], int offset, int length);
private final char value[]; // 存储值
3.2 StringBuffer(线程安全)
可变字符长度
是一个容器
- 构造
StringBuffer(int capacity);
StringBuffer(String str);
char[] values;
- 方法
public synchronized String toString();
public synchronized StringBuffer append(String str);
public synchronized StringBuffer append(StringBuffer sb);
// [start, end)
public synchronized StringBuffer delete(int start, int end);
public synchronized StringBuffer deleteCharAt(int index);
3.3 StringBuilder
与StringBuffer一样的API
但不是线程安全的
在单线程中,优先使用StringBuilder
3.4 Math
3.5 Arrays
Integer arr[] = {11, 33, 55, 22};
// sort
Arrays.sort(arr);
3.6 System/BigInteger
3.7 Date、Calendar、Local…
Date
package com.xhh05_exception;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date_ {
public static void main(String[] args) throws ParseException {
// [1] get curr system date
Date d1 = new Date();
Date d2 = new Date(10000); // 根据毫秒数计算时间
// [2] 进行格式化
SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss E");
String currtime = simp.format(d1);
System.out.println(currtime);
System.out.println(simp.format(d2));
// String -> data
String s2 = "2021-09-24 02:59:31 星期五";
Date pase = simp.parse(s2);
System.exit(0);
}
}
Local…
LocalDateTime ldt = LocalDateTime.now(); // LocalDate LocalTime
System.out.println(ldt);
4 集合
4.1 简介
4.2 Collection接口
add
remove
contains
size
isEmpty
clear
addAll // 添加多个元素
containsAll // 多个元素是否存在
removeAll //移除多个元素
4.3 Iterator 迭代器
Iterator<T> iterator();
ArrayList<Integer> arr = new ArrayList<>();
arr.add(11);
arr.add(55);
arr.add(33);
Iterator<Integer> iter = arr.iterator();
while (iter.hasNext()){
System.out.print(iter.next() + " "); // 11 55 33
}
// 简化版本的Iterator
for(Integer obj: arr){
System.out.print(obj + " "); // 11 55 33
}
4.4 List接口
- ArrayList(可变数组,线程不安全)
- Vector(线程安全)
- LinkedList(双向链表)
- Stack
boolean add(E e);
E get(int index);
E set(int index, E element);
E remove(int index);
int indexOf(Object o);
int lastIndexOf(Object o);
// [fromIndex ,toIndex)
List<E> subList(int fromIndex, int toIndex);
4.5 Set接口
- HashSet(数组+链表)
- LinkedHashSet(数组+双向链表,插入和删除顺序是一样)
- TreeSet
int size();
boolean add(E e);
boolean remove(Object o);
boolean contains(Object o);
Iterator<E> iterator();
void clear();
4.6 Map接口
- HashMap(线程不安全)
– LinkedHashMap - TreeMap
- HashTable(和HashMap接口一样,线程安全的)
– Properties
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
V get(Object key);
V put(K key, V value);
default boolean remove(Object key, Object value);
default V replace(K key, V value);
default boolean replace(K key, V oldValue, V newValue);
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
void clear();
遍历
package com.xhh06_collection_;
import java.util.*;
public class iterator_use {
public static void main(String[] args) {
HashMap hsMap = new HashMap();
hsMap.put(1, 111);
hsMap.put(2, "for_each");
hsMap.put(3, '&');
// [1] getKey -> key_value
Set keySet = hsMap.keySet();
for (Object key :keySet) {
System.out.println("key: " + key + " value:" + hsMap.get(key));
}
// [2] key_iterator
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println("key: " + key + " value:" + hsMap.get(key));
}
// [3] entrySet
Set enSet = hsMap.entrySet(); // EntrySet<Map.Entry<K,V>>
for (Object entry :enSet) {
Map.Entry em = (Map.Entry) entry;
System.out.println("key: " + em.getKey() + " value:" + em.getValue());
em.setValue(9999);
}
// [4] getValues
Collection values = hsMap.values();
for (Object v :values) {
System.out.println("value :" + v);
}
HashMap<Integer, Integer> iiMap = new HashMap<>();
iiMap.put(1, 111);
iiMap.put(2, 222);
iiMap.put(3, 333);
Set<Map.Entry<Integer, Integer>> entries = iiMap.entrySet();
for (Map.Entry em : entries) {
System.out.println("key: " + em.getKey() + " value:" + em.getValue());
if(em.getKey().equals(2)){
em.setValue(22222);
}
}
entries = iiMap.entrySet();
for (Map.Entry em : entries) {
System.out.println("key: " + em.getKey() + " value:" + em.getValue());
}
}
}
4.7 Collections 工具栏
- 静态方法
int binarySearch(List<? extends Comparable<? super T>> list, T key);
public static void reverse(List<?> list);
public static <T extends Comparable<? super T>> void sort(List<T> list);
public static <T> void sort(List<T> list, Comparator<? super T> c);
public static void swap(List<?> list, int i, int j);
Object max(Collection);
Object max(Collection, Comparator);
Object min(Collection);
Object min(Collection, Comparator);
void copy(List src, List dst);
- Demo
package com.xhh06_collection_;
import java.util.*;
public class iterator_use {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(11);
arr.add(55);
arr.add(33);
Collections.reverse(arr);
System.out.println(arr);
Collections.sort(arr); // 升序
System.out.println(arr);
Collections.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// return o1 - o2; // 升序
return o2 - o1; // 降序
}
});
System.out.println(arr);
}
}
5 泛型
class Generic<K, V>{
public Generic() {
}
public Generic(K kValue, V vValue) {
this.kValue = kValue;
this.vValue = vValue;
}
public K getkValue() {
return kValue;
}
public void setkValue(K kValue) {
this.kValue = kValue;
}
public V getvValue() {
return vValue;
}
public void setvValue(V vValue) {
this.vValue = vValue;
}
public void showInfo(){
System.out.println("kValue: " + kValue + " vValue:" + vValue);
}
private K kValue;
private V vValue;
}
Generic gen1 = new Generic();
gen1.setkValue("xhh");
gen1.setvValue(608);
gen1.showInfo();
Generic<Integer, String> gen2 = new Generic<>(18, "mcy");
gen2.showInfo();
6 多线程基础
6.1 线程基本使用
- 方法一:继承Thread类,重写run
package com.test;
import javax.swing.plaf.PanelUI;
/**
* @author : xhh
* @email : xhh0608@foxmail.com
* @date : 2021.9.24
*/
public class Thread_01 {
public static void main(String[] args) throws InterruptedException {
// [1] 创建Cat对象 可以当做线程使用
Cat xhh = new Cat("xhh");
Cat mcy = new Cat("mcy");
// [2] 启动线程 start 调用 run()
xhh.start();
mcy.start();
// [3] 主线程阻塞等待
xhh.join();
mcy.join();
System.out.println("Main ---- S-Start");
Thread.sleep(2000);
System.out.println("Main ---- S-end");
System.exit(0);
}
}
// 继承Thread 该类就是一个线程方法
class Cat extends Thread{
@Override
public void run() {
while (true){
System.out.println(name + " : miao ... idx : " + count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
if(count > 10) break;
}
}
public Cat(String name){
this.name = name;
}
public String name;
private int count = -888;
}
- 方法二:实现Runnable接口,重写run(运行采用Thread的静态代理模式)
package com.test;
/**
* @author : xhh
* @email : xhh0608@foxmail.com
* @date : 2021.9.24
*/
public class Thread_02 {
public static void main(String[] args) throws InterruptedException {
// [1] 创建Cat对象 可以当做线程使用
Dog xhh = new Dog("xhh");
Dog mcy = new Dog("mcy");
// [2] 启动线程 start 调用 run()
Thread t1 = new Thread(xhh);
Thread t2 = new Thread(mcy);
t1.start();
t2.start();
// [3] 主线程阻塞等待
t1.join();
t2.join();
System.out.println("Main ---- S-Start");
Thread.sleep(2000);
System.out.println("Main ---- S-end");
System.exit(0);
}
}
// 继承Thread 该类就是一个线程方法
class Dog implements Runnable{
@Override
public void run() {
while (true){
System.out.println(name + " : miao ... idx : " + count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
if(count > 10) break;
}
}
public Dog(String name){
this.name = name;
}
public String name;
private int count = 0;
}
6.2 线程方法
public final synchronized void setName(String name);
public final String getName();
public synchronized void start(); // 线程执行,JVM 运行 start0
public void run(); // 重写该方法
// MAX_PRIORITY MIN_* NORM_*
public final void setPriority(int newPriority);
public final int getPriority();
public long getId();
public static native void sleep(long millis) throws InterruptedException;
public void interrupt(); // 中断线程
6.3 线程的生命周期
6.4 线程同步(synchronized)
synchronized
package com.test;
/**
* @author : xhh
* @email : xhh0608@foxmail.com
* @date : 2021.9.25
*/
public class Thread_06_sync {
public static void main(String[] args) throws InterruptedException {
SellTicketV2 sell = new SellTicketV2();
Thread t1 = new Thread(sell);
Thread t2 = new Thread(sell);
// 两个线程共享static变量
t1.start();
t2.start();
t1.join();
t2.join();
}
}
//class SellTicketV2 extends Thread{ // 继承会出现问题(因为不是同一个对象)
class SellTicketV2 implements Runnable{ // 实现接口没有问题
@Override
public void run() {
while (isLoop){
runMethod(); // 同步方法
}
}
// sell synchronized method
private synchronized void runMethod(){
if(ticketNum <= 0){
isLoop = false;
System.out.println("sell over and exit loop.");
return;
}
// System.out.println("curr tid: " + this.getId() + " ticketNum: " + ticketNum);
System.out.println("curr tid: " + Thread.currentThread().getId() + " ticketNum: " + ticketNum);
ticketNum--;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// e.printStackTrace();
System.out.println("catch (InterruptedException e)");
}
}
private static int ticketNum = 20; // all ticket static for share
private boolean isLoop = true;
}
// [1] 方法快 加锁
// [2] 静态方法快 加锁
class Lock implements Runnable{
@Override
public void run() {
}
// [1] method
public void func1(){
synchronized (this){
System.out.println("do something ....");
}
}
// [2] static method
public static void func2(){
synchronized (Lock.class){
System.out.println("do something ....");
}
}
}
释放锁
参考