Java 基础
# Java OOP
面向对象编程(OOP)的三大要素
- 封装
- 继承
- 多态
一脉相承,实现逻辑闭环,这样的编码方式是符合封建直觉的
# 类与基本类型
类的拆装箱:装箱即把基本类型变量转换为引用类型变量,将存放在栈中的数据转移到堆中,完成基本类型到对象的转换,而拆箱即把引用类型转化为基本类型
- 拆箱:调用Number类中的 Value() 方法
- 装箱:调用包装类的构造方法,如
Integer(int value),调用valueOf(int value)方法(返回 Integer 对象)
int num4 = 10;
//底层实现valueOf()方法,即Integer integer4 = Integer.valueOf(num4)
Integer integer4 = num4;
//底层实现intValue()方法,即int num5 = integer4.intValue()
int num5 = integer4;
2
3
4
5
字符串与数字类型转换:使用包装类中toString方法和parseXXX方法进行转换
Integer.valueOf(int i)方法的缓冲区
为了减少内存的消耗,在value()方法内部存在一个数组,当传入的 i 在数组范围时,方法将直接从数组中提出对应的 i 赋给新的 Integer 对象,这样 new 出来的 Integer 实际上指向的是堆中的同一片区域,即数组中 i 的地址
当 i 超出缓冲区时,将重新在堆中开辟一个空间赋给 Integer 对象,Integer 缓冲区为[-128,127]
# 常用类
# Object 类
内部类
- 成员内部类:与成员属性同级
- 静态内部类:和外部类同级,但要通过外部类创建
- 局部内部类:存在于外部类的方法中
- 匿名内部类:在实现接口或使用抽象类时使用
Object 类:父类、基类(祖宗类),所有类直接或间接继承于 Object
常用方法
- getClass:返回当前类型的Class类
- hashCode:返回当前对象的哈希值
- toString:返回当前类的字符串描述(多重写)
- equals:判断是否“相等”
@Override
public boolean equals(Object obj) {
//若引用同一个对象,直接返回true
if (this == obj) return true;
//判断o是否为空
if (obj == null) return false;
//判断类型是否一致
if(obj instanceof Student) {
//强制转换类型
Student student = (Student) obj;
//比较属性
if (this.age == student.getAge() && this.name.equals(student.getName())) {
return true;
}
}
return false;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- instanceof 关键字:判断前者类型是否直接或间接属于后者,即是否存在直接创建或继承关系
- finalize:垃圾(不用的对象)回收方法(可重写)
# String
常用方法
length(); //返回字符串长度
charAt(int index); //返回某个位置的字符
contains(String str); //判断是否包含某个子字符串
toCharArray(); //将字符串转换为字符数组
indexOf(String str); //查找str首次出现的下标索引 (index:索引)
lastIndexOf(String str); //查找str最后一次出现的下表索引
trim(); //去掉字符串前后的空格 (trim:修剪)
toUpperCase(); //将小写转成大写 (upper:上面的、上部的、较高的)
endWith(String str); //判断字符串是否以str结尾
replace(char oldChar, char newChar); //将旧字符(串)替换为新字符(串)
String[] split(String str); //根据str做拆分
equals(String str); //比较两个字符串值是否相等
equalsIgnoreCase(String str); //忽略大小写比较两个字符串值是否相等
compareTo(String str); //优先返回首个ASCII码不同的字符的ASCII码大小的差,若原字符串是str从前向后的子串,则返回两个字符串长度的差(前减后)
substring(int begin, int end)/substring(int begin); //截取字符串,从第begin个字符截取到第end个字符或从begin截取到最后
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
可变字符串(较于重新在池中储存字符串更节省内存、更高效)
//StringBuffer:效率较高,线程安全
//StringBuilder:效率更高,线程不太安全(单线程随便搞)
//常用方法
append(); //追加
insert(int start); //插入
delete(int start, int end); //删除
reverse(); //翻转
replace(int start, int end, String str); //替换
2
3
4
5
6
7
8
9
# BigDecimal
原因:double、float 类型储存的是近似值,在精确计算时会出较大偏差,需要一个高精度类来进行计算
常见方法
add(BigDecimal bd):加法substract(BigDecimal bd):减法(前减后)multiply(BigDecimal bd):乘法divide(BigDecimal bd):除法(前除以后)
注意:当除法碰到除不尽的情况,使用其重载divide(BigDecimal bd, int scal, RoundingMode mode),其中
scal为精确位数RoundingMode为取舍模式 (一般为四舍五入ROUND_HALF_UP)
# 时间类型
Date 类
Date() / Date(long date):构造方法,前者获取当前时间,后者获取输入时间(以毫秒为单位)void toString():打印字符串时间int getTime():返回当前Date对象的时间int compareTo(Date d):返回前后天数之差boolean equals(Date d):判断两个时间是否相等boolean before/after(Date d):判断当前 Date 是否在 d 之前/后
Calendar 类
Calendar.instance():构造方法被保护,使用该静态方法构造 Calendar 对象Date getTime():返回一个Date对象,与原时间相同int get(field f):获取诸如年、月、日、小时、分钟、秒等时间void add():在原对象上添加或减少时间void set(field f, int d):设置时间,field 设置时间类型(年月日时分秒),d 设置时间长度int getActualMaximum(field f) / int getActualMinimum(field f):返回 f 类型在该时间的最大值,如三月的最大天数为 31
SimpleDateFormat
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSimpleDateFormat {
public static void main(String[] args) {
//创建SimpleDateFormat对象,限定格式
//y代表年,M代表月,d代表天,H代表小时,m代表分钟,s代表秒
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
//创建Date对象
Date date1 = new Date();
//格式化Date,把时间转化为字符串
String str = sdf.format(date1);
System.out.println(str);
Date date2 = new Date();
//把字符串转化为日期
try{
date2 = sdf.parse("1990年12月12日");
}
catch(ParseException p){
System.out.println("捕获到异常");
}finally{
System.out.println(date2.toLocaleString());
}
}
}
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
# System 类
常用方法
static void println():命令行输出static void arraycopy():复制数组static long currentTimeMillis():获取当前系统时间static void gc():建议 jvm 启动垃圾回收器回收垃圾static void exit(int status):手动退出 jvm,如果参数是 0 表示正常退出 jvm,非 0 则异常退出 jvm、
# 内部类和枚举
# 静态内部类
public class Holder {
private Holder(){
System.out.println(Thread.currentThread().getName() + " ok");
}
public static Holder getInstance(){
return Inner.HOLDER;
}
private static class Inner{
private static Holder HOLDER = new Holder();
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
Holder.getInstance();
}).start();
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 枚举类
enum:其本身也是一个 Class 类,一个简单较安全“数组”
public enum Beer{
WUSU, QINGDAO, ZHUJIANG
}
2
3
这实际上是一种语法糖,Enum作为一个抽象类,以上述方式定义的Beer将会继承Enum并创建一个Beer[],其中存放了三个名叫WUSU, QINGDAO, ZHUJIANG的Beer对象,同时Beer将维护一个Map<String, Beer>,键即为定义时的字符串,值即为对应的 Beer 对象
在进行拿取时
Beer currentBeer = Beer.WUSU;
也可以直接通过字符串来强转
Beer currentBeer = Beer.valueOf("WUSU");
很明显第二种方式就是在用 Map 进行拿取,键为对象名,值为对象
# 匿名内部类
众所周知,匿名内部类访问外部变量时,变量需要被声明为final,这是 Java 的语法规则决定的
- 如果允许修改外部变量,会导致内部类持有的值与外部变量的值不一致,破坏 Java 的内存模型一致性
例如如下代码,将会编译不通过,因为根本无法访问外部变量
// 这样会编译错误
int count = 0;
Runnable runnable = new Runnable() {
@Override
public void run() {
count++; // 编译错误:不能修改final变量
}
};
2
3
4
5
6
7
8
但是 final 字段能够将变量定义为“不可变”,这种不可变可以保持 Java 的内存模型一致性,那么就可以改变外部变量了
final int count = 0;
Runnable runnable = new Runnable() {
@Override
public void run() {
count++; // 编译错误:不能修改final变量
}
};
2
3
4
5
6
7
这样会编译错误,都说了 final 修饰的变量不可变,你还搁这变,包报错的
怎么办呢,我们可以用 final 修饰一个数组
// 数组方式可以修改内部值
final int[] count = {0};
Runnable runnable = new Runnable() {
@Override
public void run() {
count[0]++; // 合法,修改数组元素
System.out.println("内部类中:" + count[0]);
}
};
runnable.run();
System.out.println("外部:" + count[0]); // 输出1,体现了修改效果
2
3
4
5
6
7
8
9
10
11
12
众所周知数组是指针,final 修饰的实际上是指针,ok,那么指针是不可变的,但指针指向的值是可变的,这样就可以做到匿名内部类的修改值传递
# 异常处理
异常处理基础:错误信息的打印一定要能捕获到关键的报错原因,而不是无脑 e.getMessage,比如一个对象的构造出错,那么你要把构造的所有参数打印出来,不然还得再跑一次测试,养成好的习惯
try{
if(条件){
//当满足条件时主动抛出异常给下方捕获
throw new Exception
}
//监控区
}catch(Exception e){
//捕获异常
//处理区
}finally{
//善后区
}
void calculate(int a, int b) throws Exception //从方法内部将异常抛出
{
try{
if(b==0){
throw new Exception();
}
System.out.println(a/b);
}catch(Exception e){
return;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
自定义异常类
package com.Exception;
//自定义的异常类,继承java自带的Exception
public class MyException extends Exception
{
private int detail;
public MyException(int x)
{
this.detail = x;
}
//打印异常信息
@Override
public String toString()
{
return "MyException{" + "detail=" + detail + '}';
}
}
class Test
{
static void test(int x) //throws MyException(也可以用throws将异常抛出函数外)
{
System.out.println("传递的数为:" + x);
try
{
if(x > 10)
{
throw new MyException(x);
}
} //在函数内部捕获监控区内异常并处理
catch (MyException e)
{
System.out.println("MyException=>" + e);
}
System.out.println("OK");
}
public static void main(String[] args)
{
int a = 11;
// try
// {
new Test().test(a);
/* }
catch (MyException e)
{
System.out.println("MyException=>" + e);
}*/
}
}
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
# Java 集合
Generic 泛型接口
interface MyInterface<T> {
//接口可创建静态常量
String name = "NorthBoat";
void build(T t);
void show();
}
class MyInterfaceImpl1 implements MyInterface<String> {
private String str;
@Override
public void build(String s) {
str = s;
}
@Override
public void show() {
System.out.println(str.toString());
}
}
class MyInterfaceImpl2<T> implements MyInterface<T> {
T skt;
@Override
public void build(T t) {
skt = t;
}
@Override
public void show() {
System.out.println(skt);
}
}
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
泛型类
class MyGeneric<T> {
T t;
void setT(T t1) {
t = t1;
}
void show() {
System.out.println(t.toString());
}
}
2
3
4
5
6
7
8
9
10
11
12
Collection 接口
size():返回元素个数
add(Object obj):添加元素
remove(Object obj):删除元素
clear():清空容器
toString():返回元素的字符串表现形式
equals(Object obj):判断两个容器是否相等
isEmpty():判断容器是否为空
Iterator():返回当前容器的迭代器
遍历
- 用增强版的 for 循环(Collection 无下标:不能用 for):
for(Object obj: arraylist){} - 用迭代器遍历(专门用来遍历集合的一种方式)
Iterator it = collection.iterator();//创建迭代器
while(it.hasNext){
Student s = (Student)it.next();//类型强制转换(Obj到具体类)
sout(s.toString);//打印
}
2
3
4
5
Iterator:迭代器
- hasNext():判断容器中是否有下一个元素
- next(): 返回容器中下一个元素
- remove(): 把当前元素删除
// List的迭代器
ListIterator lt = list.listIterator();
while(lt.hasNext()){
System.out.println(lt.next().toString());
}
2
3
4
5
List:动态数组,有序、有下标
- ArrayList:内部维护一个数组(查找快,增删慢),默认初始容量 10,常用方法:add、remove、get、isEmpty、contains
- LinkedList:内部维护一个双向链表(查找慢,增删快)
- Vector:线程安全的数组
ArrayList:当达到数组上限时创建一个 1.5 倍大小的新数组,用 System 中 arrayCopy 方法复制原来元素至新数组
Set:集合,无序、无下标、无重复元素
- HashSet:内部维护一个哈希表(数组 + 链表 + 红黑树),利用 hashcode() 和 equals() 实现不重复
- SortedSet → TreeSet,存储结构:红黑树 → 中序遍历(二叉搜索),基于排序顺序实现元素不重复,通过实现 SortedSet 接口,对集合元素自动排序
TreeSet 的排序规则
- 用 Comparable 接口中 CompareTo() 方法作为排序标准:在类中重写,当 CompareTo() 返回值为 0 时,判断两者相同
- 利用 TreeSet 含 Comparator 接口(比较器)的构造方法,在 Comparator 的匿名内部类中重写 compare() 方法,实现比较规则的定义
TreeSet<String> tree = new TreeSet<>(new Comparator<String>(){
@Override
public int compare(String s1, String s2){
int n1 = s1.length()-s2.length();
int n2 = s1.compareTo(s2);
return n1==0?n2:n1;
}
});
2
3
4
5
6
7
8
9
10
Map:哈希表
put (k key, v value)
remove(k key)
keySet()
entrySet()
size()
containsKey(k key)
containsValue(v value)
Entry:Map 中的静态内部类,储存 key 和 value 的键值对<key, value>
- Entry 常用方法:
getKey() / getValue()
HashMap 示例
/**
* 存储结构:哈希表
* 默认初始容量:16(1<<4) 加载因子:0.75(扩容比例)
* 存储结构:哈希表(数组+链表+红黑树)
* 线程不安全,效率高,允许null作为键和值
*/
public class TestHashMap {
public static void main(String[] args) {
HashMap<Student, Integer> hashmap = new HashMap<>();
Student s1 = new Student("Rose", 32);
Student s2 = new Student("Harden", 33);
Student s3 = new Student("Wade", 38);
hashmap.put(s1, 1);
hashmap.put(s2, 13);
hashmap.put(s3, 3);
//覆盖了第一个s1
hashmap.put(s1, 25);
//加进了hashmap ——> 改写掉Student的hashcode和equals方法规定重复规则 ——> 又覆盖了s1
hashmap.put(new Student("Rose", 32), 4);
System.out.println("元素个数:" + hashmap.size());
System.out.println(hashmap.toString());
//删除
hashmap.remove(s3);
System.out.println(hashmap.toString());
System.out.println("-------------");
//遍历(重点)
for(Student stu: hashmap.keySet()){
System.out.println(stu.toString() + ", " + hashmap.get(stu));
}
System.out.println("-------------");
for(Map.Entry<Student, Integer> entry: hashmap.entrySet()){
System.out.println(entry.getKey() + ", " + entry.getValue());
}
System.out.println("-------------");
//判断
System.out.println(hashmap.containsKey(s1));
System.out.println(hashmap.containsValue(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
基本属性
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
Node<K, V> next;//单向指针
transient Node<K,V>[] table;//数组
transient int size;//元素个数
2
3
4
5
6
7
8
9
源码总结
初始容量:1 << 4(16)
最大容量:1 << 30(2 的 30 次方)
当容量达到 75% 时开始扩容
当链表(单向)长度大于 8 并且数组长度大于 64 时,开始形成红黑树,以提高查找效率
当链表长度小于 6 时,将红黑树重新展开为链表
JDK1.8 之前,链表为头插入,1.8 之后为尾插入
HashMap 和 HashSet
- HashSet 内部维护了一个 HashMap
Hashtable
- 存储结构:哈希表
- 可以用枚举器、keySet、entrySet 遍历
Properties
- Properties 为 Hashtable 的子类,要求 key 和 value 均为 String 类
- 与"流"密切相关
TreeMap
- 存储结构:红黑树
- 可以对 key 进行自动排序,与 TreeSet 类似,同样要求实现 Comparable 接口中 compareTo 方法,或使用 Comparator 的匿名内部类定制比较器
自定义比较器
//实现Comparable接口
public class Student implements Comparable<Student>{
private String name;
private int age;
@Override
public int compareTo(Student o) {
int n1 = this.name.compareTo(o.getName());
int n2 = this.age-o.getAge();
return n1==0?n1:n2;
}
}
//定制比较器
TreeMap<Teacher, String> treemap = new TreeMap<>(new Comparator<Teacher>(){
@Override
public int compare(Teacher o1, Teacher o2) {
int n1 = o1.getName().compareTo(o2.getName());
int n2 = o1.getAge()- o2.getAge();
return n1==0?n1:n2;
}
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
与 TreeSet 关系:在 TreeSet 内部维护了一个 NavigableMap 对象 m,即 TreeMap,TreeSet 的 add 方法实际上调用了 m 的 put 方法(😓)
Collections 工具:由 Collection 中一系列静态方法组成
- sort:对集合升序排列,必须实现 Comparable 接口
//sort()排序
Collections.sort(list);
System.out.println(list.toString());
2
3
- binarySearch:二分查找,返回元素位置
//binarySearch()二分查找:返回下标 必须要sort后才能二分查找
int i = Collections.binarySearch(list, 95);
System.out.println(i);
2
3
- copy:reverse
//reverse(list)反转
Collections.reverse(list);
System.out.println(list.toString());
2
3
- shuffle:洗牌,打乱元素顺序
//shuffle(list)洗牌:将元素顺序打乱
Collections.shuffle(list);
System.out.println(list.toString());
2
3
- list.toArray:集合转成数组
//集合转成数组
Integer[] arr = list.toArray(new Integer[0]);
for(int z = 0; z < arr.length; z++){
System.out.println(arr[z]);
}
2
3
4
5
- asList:数组转成集合
//数组转成集合
String[] str = {"张三", "李四", "王五"};
List<String> list1 = Arrays.asList(str);
System.out.println(list1.toString());
2
3
4
注意
- 通过 asList 构造的集合是一个受限集合,不能进行添加和删除
- 把基本类型转化成集合时,要把其修改为包装类
# Java 程序打包
打包为 War / Jar 包
jar -cvf myapp.jar *
jar -cvf myapp.jar *
2
Jar 包启动与关闭
nohup java -jar xxxx.jar --server.port=8080 >log.txt &
ps -ef | grep java
kill -9 podId
2
3
4
Jar 包转 EXE,将可运行的 jar 包转成自带环境的可运行 exe 文件
- Exe4j:使用 Exe4j 打包 Jar 包为可执行 EXE 文件
- Inno Setup:使用 inno setup 打包可执行 EXE 文件和运行环境为安装包文件
日常使用的 JDK 的 jre 略大,会造成最终程序较大(>200MB),可使用精简版的 jre 进行打包
# Java 输入输出
# 命令行 I/O
Scanner:命令行输入
import java.util.Scanner;
/**
* @author NorthBoat
* @version 1.8
*/
public class TestScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数据:");
/*
if(scanner.hasNext()){ //判断是否有数据输入,以空格作为结束符
String str = scanner.next();
System.out.println(str);
}
*/
int a = scanner.nextInt();
String b = scanner.nextString();
double c = scanner.nextDouble();
if(scanner.hasNextLine()){ //判断是否有数据输入,以回车作为结束符(平时常用nextLine())
String str = scanner.nextLine();
System.out.println(str);
}
scanner.close();
}
}
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
命令行输出非常简单:sout → System.out.println()
# I/O 流
流:数据从内存和存储设备之间的通道
输入输出流:以流的流向分类
- 输入流:从存储设备到内存
- 输出流:从内存到存储设备
字节字符流:以传输单位划分
- 字节流:以字节为单位,可以读写所要数据
- 字符流:以字符为单位,只能读写文本数据
节点(底层)过滤流:按功能划分
- 节点流:具有实际传输数据的读写功能的流
- 过滤流:在节点流的基础上增强了功能
# 字节 I/O 流
InputStream:输入流抽象类
int available();
//关闭流的资源
void close();
//读取下一个字节
abstract int read();
//读取一定量的字节
int read(byte[] b);
int read(byte[] b, int off, int len);
//跳过和丢弃n个字节
long skip(long n);
2
3
4
5
6
7
8
9
10
OutputStream:输出流抽象类
void close();
//刷新缓冲
void flush();
//将字节写入磁盘
void write(byte[] b);
void write(int b);
2
3
4
5
6
# 文件字节流
FileInputStream
class FileInputStream extends InputStream{
//从文件系统中的某个文件中获得输入字节,将读到内容存入b数组,返回实际读到的字节数,如果达到文件的尾部,则返回-1
FileInputStream(String name);
public int read(byte[] b);
}
2
3
4
5
public class TestFileInputStream {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("E:\\Java\\Java SE\\idea\\src\\resource\\a.txt");
//一次读取一个字节
/*
* int data = 1;
* 一次读取一个字节
* 用循环将文件读完(当读到文件末尾将返回-1)
* while(data != -1){
* data = fis.read();
* System.out.println((char)data);
* }
*/
//一次读取多个字节
byte[] b = new byte[3];
int count;
while((count = fis.read(b)) != -1){
System.out.println(new String(b, 0, count));
}
//关闭输入流
fis.close();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
FileOutputStream
class FileOutputStream extends OutputStream
//一次写入多个字节,将b数组中所有字节写入输出流,存到文件系统的某个文件中
public void write(byte[] b);
}
2
3
4
import java.io.FileOutputStream;
public class TestFileOutputStream {
public static void main(String[] args) throws Exception {
//append参数true会使文件不会被覆盖,即每次运行都会继续储存在上次数据之后
//不传入参数或传入false,每次写文件,将会覆盖掉之前数据
FileOutputStream fos = new FileOutputStream("E:\\Java\\Java SE\\idea\\src\\resource\\b.txt", false);
/*
* 一次执行一个字符
* fos.write('a');
* fos.write('9');
* fos.write('s');
*/
String str = "helloWorld\n";
//调用字符串的 getBytes() 方法将字符串转化为字节数组
fos.write(str.getBytes());
fos.close();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 多线程基础
Process(进程)与Thread(线程)
进程 = 指令执行序列 + 资源
# Java 创建线程
推荐使用 Runnerable 接口
# 继承 Thread 类
实现了 Runnerable 接口,每个线程的优先级和操作系统有关
- 自定义线程类继承 Thread 类
- 重写 run() 方法,编写线程执行体
- 创建线程对象,调用 start() 方法启动线程
public class TestThread extends Thread{
@Override
public void run() {
for(int i = 0; i < 1000; i++){
System.out.println("我在看代码");
}
}
public static void main(String[] args) {
TestThread tt = new TestThread();
//调用start方法,两个线程是同时执行的
tt.start();
for(int i = 0; i < 1000; i++){
System.out.println("我在拉屎");
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
如何导入外部jar包
- 在 com 同级目录下新建 lib 目录,将 jar 包粘贴进去
- 添加 lib 为 library
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.net.URL;
public class TestThread2 extends Thread{
private String url;
private String name;
public TestThread2(String url, String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader wd = new WebDownloader();
wd.downloader(this.url, this.name);
System.out.println("正在下载:" + this.name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://img-blog.csdnimg.cn/2019080416083639.png", "图片1.jpg");
TestThread2 t2 = new TestThread2("https://img-blog.csdnimg.cn/2019080416083639.png", "图片2.jpg");
TestThread2 t3 = new TestThread2("https://img-blog.csdnimg.cn/2019080416083639.png", "图片3.jpg");
TestThread2 t4 = new TestThread2("https://img-blog.csdnimg.cn/2019080416083639.png", "图片4.jpg");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
//在lib中导入了外部jar包
class WebDownloader{
public void downloader(String url, String name){
try{
FileUtils.copyURLToFile(new URL(url), new File(name));
}catch(Exception e) {
e.printStackTrace();
}
}
}
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
# 实现 Runnerable 接口
public class TestThread3 implements Runnable {
@Override
public void run() {
for(int i = 0; i < 1200; i++){
System.out.println("我在拉屎" + i);
}
}
public static void main(String[] args) {
TestThread3 t = new TestThread3();
new Thread(t).start();
for(int i = 0; i < 1200; i++){
System.out.println("我在吃饭" + i);
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 实现 Callable 接口
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestCallable implements Callable<String> {
private String url;
private String name;
public TestCallable(String url, String name){
this.url = url;
this.name = name;
}
@Override
public String call() {
WebDownloader wd = new WebDownloader();
wd.downloader(this.url, this.name);
System.out.println("正在下载:" + this.name);
return name+"下载完成";
}
public static void main(String[] args) {
TestCallable t1 = new TestCallable("https://img-blog.csdnimg.cn/2019080416083639.png", "图片1.jpg");
TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/2019080416083639.png", "图片2.jpg");
TestCallable t3 = new TestCallable("https://img-blog.csdnimg.cn/2019080416083639.png", "图片3.jpg");
TestCallable t4 = new TestCallable("https://img-blog.csdnimg.cn/2019080416083639.png", "图片4.jpg");
//创建线程池服务
ExecutorService ser = Executors.newFixedThreadPool(4);
//提交线程服务,在池中执行call方法
Future<String> f1 = ser.submit(t1);
Future<String> f2 = ser.submit(t2);
Future<String> f3 = ser.submit(t3);
Future<String> f4 = ser.submit(t4);
//获取call函数的返回结果
try{
String res1 = f1.get();
String res2 = f2.get();
String res3 = f3.get();
String res4 = f4.get();
}catch(Exception e){
e.printStackTrace();
}
//停止线程池
ser.shutdownNow();
}
}
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
# 线程并发
多个线程操作一个对象
public class TestThread4 implements Runnable{
private int tickets = 100;
public void run(){
while(true){
if(tickets <= 0)
break;
System.out.println(TestThread2.currentThread().getName() + "抢到了第" + tickets-- + "张票");
}
}
public static void main(String[] args) {
TestThread4 tickets = new TestThread4();
new Thread(tickets, "小明").start();
new Thread(tickets, "小红").start();
new Thread(tickets, "黄牛").start();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
在实际运行中,发现居然出现某某抢到了 -1 张票的情况,存在问题:多个线程操作同一个对象,线程不安全,数据紊乱
模拟龟兔赛跑
public class Race implements Runnable {
private static String winner;
public void run(){
for (int i = 0; i <= 100; i++) {
if(Thread.currentThread().getName().equals("兔子") && i >= 80){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
}
if(gameOver(i)){
break;
}
System.out.println(Thread.currentThread().getName() + "跑了" + i + "米");
}
}
public boolean gameOver(int i){
if(winner != null){
return true;
}
else{
if(i >= 100){
winner = Thread.currentThread().getName();
System.out.println("获胜者是:" + winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race r = new Race();
new Thread(r, "兔子").start();
new Thread(r, "乌龟").start();
}
}
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
# 线程休眠与礼让
Thread.sleep() 方法:在游戏中添加一句 sleep,充值后去掉这行代码实现“游戏优化”,逆天
- 让线程阻塞,传入阻塞时间参数,单位毫秒抛出异常
InterruptedException - 当 sleep 时间达到后线程将处于就绪状态,sleep 可以模拟网络延时,倒计时等
- 每个对象都要一个锁,sleep不会释放锁
Thread.yield() 方法
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将现场从运行状态转为就绪状态
- 让 cpu 重新调度,但不一定成功
# 函数式接口
新的编程风格:lambda 表达式、链式编程、函数式接口、Stream 流式计算
函数式接口:只有一个方法的接口,比如 Runnable / Callable
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
//新版java中有很多很多FunctionalInterface
//简化编程模型,再新版本的框架底层大量应用
//forEach(消费者类的函数式接口)
2
3
4
5
6
7
8
# Function 函数型
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
2
3
4
5
6
7
8
9
10
11
有一个传入参数,有一个返回值(均为泛型,默认Object),仅含一个方法:apply (Object o, Object b)
import java.util.function.Function;
public class FunctionTest {
public static void main(String[] args) {
/**用匿名内部类重写apply函数
* Function<String, String> f = new Function<String, String>() {
* @Override
* public String apply(String str) {
* return str;
* }
* };
*/
//用lambda表达式简化
Function<String, String> function = (str)->{return str;};
System.out.println(function.apply("daslkfj"));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Predicate 断定型
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
2
3
4
5
6
7
8
9
10
11
12
传入一个参数(默认Object),返回一个布尔值,所含方法为 test
import java.util.function.Predicate;
public class PredicateTest {
public static void main(String[] args) {
/**
* Predicate p = new Predicate() {
* @Override
* public boolean test(Object o) {
* return o.toString().isEmpty();
* }
* };
*/
Predicate<String> predicate = (str)->{return str.isEmpty();};
System.out.println(predicate.test("alksd"));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Consumer 消费型
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
2
3
4
5
6
7
8
9
10
消费者只有输入,没有返回值(消费)
import java.util.function.Consumer;
public class ConsumerTest {
public static void main(String[] args) {
Consumer<String> consumer = (str) -> {System.out.println(str);};
consumer.accept("daskfj");
}
}
2
3
4
5
6
7
8
# Supplier 供给型
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
2
3
4
5
6
7
8
9
10
供给者没有输入,只有返回值(供给)
import java.util.concurrent.*;
import java.util.function.Supplier;
public class SupplierTest {
public static void main(String[] args) {
Supplier<String> supplier = ()->{return Thread.currentThread().getName();};
ExecutorService executorService = new ThreadPoolExecutor(
3,
12,
5,
TimeUnit.SECONDS,
new ArrayBlockingQueue(9),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
for (int i = 0; i < 12; i++) {
executorService.execute(()->{
System.out.println(supplier.get());
});
}
executorService.shutdown();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23