java基础篇章2
1.1 异常
java的异常处理机制
Object
Object下有Throwable(可抛出的)
Throwable下有两个分支:Error(不可处理,直接退出JVM)和
Exception(可处理的)
Exception下有两个分支:
编译时异常(受检异常:CheckedException、受控异常):
要求程序员在编写程序阶段必须预先对这些异常进行处理,
如果不处理编译器报错,因此得名编译时异常。
包括Exception,但不包括其子类RuntimeException
运行时异常(未受检异常:UnCheckedException、非受控异常):
在编写程序阶段程序员可以预先处理,也可以不管,都行
包括:RuntimeException及其子类
编译时异常和运行时异常,都是发生在运行阶段。编译阶段
异常是不会发生的。
编译时异常因为什么而得名?
因为编译时异常必须在编译(编写)阶段预先处理,如果不处理编
译器报错,因此得名。
所有异常都是在运行阶段发生的。因为只有程序运行阶段才
可以new对象。
因为异常的发生就是new异常对象。
编译时异常和运行时异常的区别?
编译时异常一般发生的概率比较高。
运行时异常一般发生的概率比较低。
Java语言中对异常的处理包括两种方式:
第一种方式:在方法声明的位置上,使用throws关键字,抛给上一级。
谁调用我,我就抛给谁。抛给上一级。
第二种方式:使用try..catch语句进行异常的捕捉。
这件事发生了,谁也不知道,因为我给抓住了。
注意:Java中异常发生之后如果一直上抛,最终抛给了main方
法,main方法继续
向上抛,抛给了调用者JVM,JVM知道这个异常发生,只有
一个结果。终止java程序的执行。
手动new出异常跟正常代码一样,不会影响下面代码的执行.
import java. io. IOException ;
public class Test {
public static void main ( String [ ] args) {
aa ( ) ;
System . out. println ( "Hello World" ) ;
}
static void aa ( ) {
IOException ioException = new IOException ( "手动new出异常" ) ;
}
}
运行结果:Hello World
非手动new出异常则底层会帮我们产生相应的异常,然
后抛给调用者,如果调用者不处理,则运行会报错,下面
的代码就不会执行
未处理
public class Test {
public static void main ( String [ ] args) {
aa ( ) ;
System . out. println ( "Hello World" ) ;
}
static void aa ( ) {
int i = 1 / 0 ;
}
}
运行结果:Exception in thread "main" java.lang.ArithmeticException: / by zero
处理后
public class Test {
public static void main ( String [ ] args) {
try {
aa ( ) ;
System . out. println ( "Hello World1" ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
System . out. println ( "Hello World2" ) ;
}
static void aa ( ) {
int i = 1 / 0 ;
}
}
运行结果:
java.lang.ArithmeticException: / by zero
at com.yao.Test.aa(Test.java:18)
at com.yao.Test.main(Test.java:6)
Hello World2
1.1.1 对异常的进一步理解
package com. yxj. javase. exception ;
public class ExceptionTest04 {
public static void main ( String [ ] args) {
}
public static void doSome ( ) throws ClassNotFoundException {
System . out. println ( "doSome!!!!" ) ;
}
}
package com. yxj. javase. exception ;
public class ExceptionTest05 {
public static void main ( String [ ] args) {
try {
doSome ( ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
}
public static void doSome ( ) throws ClassNotFoundException {
System . out. println ( "doSome!!!!" ) ;
}
}
package com. yxj. javase. exception ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
注意:
只要异常没有捕捉,采用上抛的方式,此方法的后续代码不会执行。
另外需要注意,try 语句块中的某一行出现异常,该行后面的代码不会执行。
try . . catch 捕捉异常之后,后续代码可以执行。
在以后的开发中,处理编译时异常,应该上抛还是捕捉呢,怎么选?
如果希望调用者来处理,选择throws 上抛。
其它情况使用捕捉的方式。
* /
public class ExceptionTest06 {
public static void main ( String [ ] args) {
System . out. println ( "main begin" ) ;
try {
m1 ( ) ;
System . out. println ( "hello world!" ) ;
} catch ( FileNotFoundException e) {
System . out. println ( "文件不存在,可能路径错误,也可能该文件被删除了!" ) ;
System . out. println ( e) ;
}
System . out. println ( "main over" ) ;
}
private static void m1 ( ) throws FileNotFoundException {
System . out. println ( "m1 begin" ) ;
m2 ( ) ;
System . out. println ( "m1 over" ) ;
}
private static void m2 ( ) throws FileNotFoundException {
System . out. println ( "m2 begin" ) ;
m3 ( ) ;
System . out. println ( "m2 over" ) ;
}
private static void m3 ( ) throws FileNotFoundException {
new FileInputStream ( "D:\\course\\01-课\\学习方法.txt" ) ;
System . out. println ( "如果以上代码出异常,这里会执行吗??????????????????不会!!!" ) ;
}
}
package com. yxj. javase. exception ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
public class ExceptionTest07 {
public static void main ( String [ ] args) {
try {
FileInputStream fis = new FileInputStream ( "D:\\curse\\02-JavaSE\\document\\JavaSE进阶讲义\\JavaSE进阶-01-面向对象.pdf" ) ;
System . out. println ( 100 / 0 ) ;
} catch ( FileNotFoundException | ArithmeticException | NullPointerException e) {
System . out. println ( "文件不存在?数学异常?空指针异常?都有可能!" ) ;
}
}
}
1.1.2 获取异常的两个非常重要的方法
package com. yxj. javase. exception ;
public class ExceptionTest08 {
public static void main ( String [ ] args) {
NullPointerException e = new NullPointerException ( "空指针异常fdsafdsafdsafds" ) ;
String msg = e. getMessage ( ) ;
System . out. println ( msg) ;
e. printStackTrace ( ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
System . out. println ( "i = " + i) ;
}
System . out. println ( "Hello World!" ) ;
}
}
1.1.3 关于try…catch中的finally子句
package com. yxj. javase. exception ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
public class ExceptionTest10 {
public static void main ( String [ ] args) {
FileInputStream fis = null ;
try {
fis = new FileInputStream ( "D:\\course\\02-JavaSE\\document\\JavaSE进阶讲义\\JavaSE进阶-01-面向对象.pdf" ) ;
String s = null ;
s. toString ( ) ;
System . out. println ( "hello world!" ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( NullPointerException e) {
e. printStackTrace ( ) ;
} finally {
System . out. println ( "hello 浩克!" ) ;
if ( fis != null ) {
try {
fis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
System . out. println ( "hello kitty!" ) ;
}
}
finally 面试题
package com. yxj. javase. exception ;
public class ExceptionTest13 {
public static void main ( String [ ] args) {
int result = m ( ) ;
System . out. println ( result) ;
}
public static int m ( ) {
int i = 100 ;
try {
return i;
} finally {
i++ ;
}
}
}
1.1.4 final finally finalize有什么区别
final 关键字
final修饰的类无法继承
final修饰的方法无法覆盖
final修饰的变量不能重新赋值。
finally 关键字
和try一起联合使用。
finally语句块中的代码是必须执行的。
finalize 标识符
是一个Object类中的方法名。
这个方法是由垃圾回收器GC负责调用的。
package com. yxj. javase. exception ;
public class ExceptionTest14 {
public static void main ( String [ ] args) {
final int i = 100 ;
try {
} finally {
System . out. println ( "finally...." ) ;
}
Object obj;
}
}
final class A {
public static final double MATH_PI = 3.1415926 ;
}
class B {
public final void doSome ( ) {
}
}
1.1.5 异常总结
public class ExceptionTest {
public static void main ( String [ ] args) {
test ( ) ;
System . out. println ( "不执行" ) ;
}
static void test ( ) {
int i = 1 / 0 ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
运行结果: Exception in thread "main" java. lang. ArithmeticException: / by zero
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ExceptionTest {
public static void main ( String [ ] args) {
try {
test ( ) ;
} catch ( Exception e) {
}
System . out. println ( "执行" ) ;
}
static void test ( ) {
int i = 1 / 0 ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
运行结果: 执行
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ExceptionTest {
public static void main ( String [ ] args) {
NullPointerException nullPointerException = new NullPointerException ( ) ;
ClassNotFoundException classNotFoundException = new ClassNotFoundException ( ) ;
System . out. println ( "普通对象" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
运行结果: 普通对象
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ExceptionTest {
public static void main ( String [ ] args) {
test ( ) ;
System . out. println ( "不执行" ) ;
}
static void test ( ) {
throw new NullPointerException ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
运行结果: Exception in thread "main" java. lang. NullPointerException
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ExceptionTest {
public static void main ( String [ ] args) {
try {
test ( ) ;
} catch ( Exception e) {
}
System . out. println ( "执行" ) ;
}
static void test ( ) {
throw new NullPointerException ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
运行结果: 执行
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ExceptionTest {
public static void main ( String [ ] args) {
try {
test ( ) ;
} catch ( ClassNotFoundException e) {
}
System . out. println ( "编译时异常" ) ;
}
static void test ( ) throws ClassNotFoundException {
throw new ClassNotFoundException ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
运行结果: 编译时异常
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ExceptionTest {
public static void main ( String [ ] args) {
test ( ) ;
System . out. println ( "执行" ) ;
}
static void test ( ) {
try {
throw new ClassNotFoundException ( ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
运行结果: java. lang. ClassNotFoundException
执行
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Test {
public static void main ( String [ ] args) {
try {
aa ( ) ;
System . out. println ( "Hello World1" ) ;
} catch ( NullPointerException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "Hello World2" ) ;
}
static void aa ( ) throws ClassNotFoundException {
int i = 1 / 0 ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
编译不通过, 没运行结果.
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
2.1 集合
集合概述
集合不能直接存储基本数据类型,另外集合也不能直接存储java对象,
集合当中存储的都是java对象的内存地址。(或者说集合中存
储的是引用。)
list.add(100); //自动装箱Integer
注意:
集合在java中本身是一个容器,是一个对象。
集合中任何时候存储的都是“引用”。
1、掌握Map接口中常用方法。
2、遍历Map集合的两种方式都要精通。
第一种:获取所有key,遍历每个key,通过key获取value.
第二种:获取Set<Map.Entry>即可,遍历Set集合中的Entry
调用entry.getKey() entry.getValue()
3、了解哈希表数据结构。
4、存放在HashMap集合key部分和HashSet集合中的元
素需要同时重写hashCode和equals。
5、HashMap和Hashtable的区别。
HashMap:
初始化容量16,扩容2倍。
加载因子为0.75f
非线程安全
key和value可以为null。
Hashtable
初始化容量11,扩容2倍+1
加载因子为0.75f
线程安全
key和value都不能是null。
6、Properties类的常用两个方法。
setProperty
getProperty
8、TreeMap的key或者TreeSet集合中的元素要想排序,有
两种实现方式:
第一种:实现java.lang.Comparable接口。
第二种:单独编写一个比较器Comparator接口。
9、集合工具类Collections:
synchronizedList方法
sort方法(要求集合中元素实现Comparable接口。)
2.1.1 Collection
2.1.2 Map
2.1.3 Collection中的常用方法
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Collection ;
public class CollectionTest01 {
public static void main ( String [ ] args) {
Collection c = new ArrayList ( ) ;
c. add ( 1200 ) ;
c. add ( 3.14 ) ;
c. add ( new Object ( ) ) ;
c. add ( new Student ( ) ) ;
c. add ( true ) ;
System . out. println ( "集合中元素个数是:" + c. size ( ) ) ;
c. clear ( ) ;
System . out. println ( "集合中元素个数是:" + c. size ( ) ) ;
c. add ( "hello" ) ;
c. add ( "world" ) ;
c. add ( "浩克" ) ;
c. add ( "绿巨人" ) ;
c. add ( 1 ) ;
boolean flag = c. contains ( "绿巨人" ) ;
System . out. println ( flag) ;
boolean flag2 = c. contains ( "绿巨人2" ) ;
System . out. println ( flag2) ;
System . out. println ( c. contains ( 1 ) ) ;
System . out. println ( "集合中元素个数是:" + c. size ( ) ) ;
c. remove ( 1 ) ;
System . out. println ( "集合中元素个数是:" + c. size ( ) ) ;
System . out. println ( c. isEmpty ( ) ) ;
c. clear ( ) ;
System . out. println ( c. isEmpty ( ) ) ;
c. add ( "abc" ) ;
c. add ( "def" ) ;
c. add ( 100 ) ;
c. add ( "helloworld!" ) ;
c. add ( new Student ( ) ) ;
Object [ ] objs = c. toArray ( ) ;
for ( int i = 0 ; i < objs. length; i++ ) {
Object o = objs[ i] ;
System . out. println ( o) ;
}
}
}
class Student {
}
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Collection ;
import java. util. HashSet ;
import java. util. Iterator ;
public class CollectionTest03 {
public static void main ( String [ ] args) {
Collection c1 = new ArrayList ( ) ;
c1. add ( 1 ) ;
c1. add ( 2 ) ;
c1. add ( 3 ) ;
c1. add ( 4 ) ;
c1. add ( 1 ) ;
Iterator it = c1. iterator ( ) ;
while ( it. hasNext ( ) ) {
Object obj = it. next ( ) ;
System . out. println ( obj) ;
}
Collection c2 = new HashSet ( ) ;
c2. add ( 100 ) ;
c2. add ( 200 ) ;
c2. add ( 300 ) ;
c2. add ( 90 ) ;
c2. add ( 400 ) ;
c2. add ( 50 ) ;
c2. add ( 60 ) ;
c2. add ( 100 ) ;
Iterator it2 = c2. iterator ( ) ;
while ( it2. hasNext ( ) ) {
System . out. println ( it2. next ( ) ) ;
}
}
}
2.1.4 深入Collection集合的contains方法
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Collection ;
public class CollectionTest04 {
public static void main ( String [ ] args) {
Collection c = new ArrayList ( ) ;
String s1 = new String ( "abc" ) ;
c. add ( s1) ;
String s2 = new String ( "def" ) ;
c. add ( s2) ;
System . out. println ( "元素的个数是:" + c. size ( ) ) ;
String x = new String ( "abc" ) ;
System . out. println ( c. contains ( x) ) ;
}
}
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Collection ;
public class CollectionTest05 {
public static void main ( String [ ] args) {
Collection c = new ArrayList ( ) ;
User u1 = new User ( "jack" ) ;
c. add ( u1) ;
User u2 = new User ( "jack" ) ;
System . out. println ( c. contains ( u2) ) ;
c. remove ( u2) ;
System . out. println ( c. size ( ) ) ;
Collection cc = new ArrayList ( ) ;
String s1 = new String ( "hello" ) ;
cc. add ( s1) ;
String s2 = new String ( "hello" ) ;
cc. remove ( s2) ;
System . out. println ( cc. size ( ) ) ;
}
}
class User {
private String name;
public User ( ) { }
public User ( String name) {
this . name = name;
}
public boolean equals ( Object o) {
if ( o == null || ! ( o instanceof User ) ) return false ;
if ( o == this ) return true ;
User u = ( User ) o;
return u. name. equals ( this . name) ;
}
}
2.1.5 关于集合元素的remove
package com. . javase. collection;
import java. util. ArrayList ;
import java. util. Collection ;
import java. util. Iterator ;
public class CollectionTest06 {
public static void main ( String [ ] args) {
Collection c = new ArrayList ( ) ;
Iterator it = c. iterator ( ) ;
c. add ( 1 ) ;
c. add ( 2 ) ;
c. add ( 3 ) ;
Collection c2 = new ArrayList ( ) ;
c2. add ( "abc" ) ;
c2. add ( "def" ) ;
c2. add ( "xyz" ) ;
Iterator it2 = c2. iterator ( ) ;
while ( it2. hasNext ( ) ) {
Object o = it2. next ( ) ;
it2. remove ( ) ;
System . out. println ( o) ;
}
System . out. println ( c2. size ( ) ) ;
}
}
2.1.6 List接口中常用方法
计算机英语:
增删改查这几个单词要知道:
增:add、save、new
删:delete、drop、remove
改:update、set、modify
查:find、get、query、select
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Iterator ;
import java. util. LinkedList ;
import java. util. List ;
public class ListTest01 {
public static void main ( String [ ] args) {
List myList = new ArrayList ( ) ;
myList. add ( "A" ) ;
myList. add ( "B" ) ;
myList. add ( "C" ) ;
myList. add ( "C" ) ;
myList. add ( "D" ) ;
myList. add ( 1 , "KING" ) ;
Iterator it = myList. iterator ( ) ;
while ( it. hasNext ( ) ) {
Object elt = it. next ( ) ;
System . out. println ( elt) ;
}
Object firstObj = myList. get ( 0 ) ;
System . out. println ( firstObj) ;
for ( int i = 0 ; i < myList. size ( ) ; i++ ) {
Object obj = myList. get ( i) ;
System . out. println ( obj) ;
}
System . out. println ( myList. indexOf ( "C" ) ) ;
System . out. println ( myList. lastIndexOf ( "C" ) ) ;
myList. remove ( 0 ) ;
System . out. println ( myList. size ( ) ) ;
System . out. println ( "====================================" ) ;
myList. set ( 2 , "Soft" ) ;
for ( int i = 0 ; i < myList. size ( ) ; i++ ) {
Object obj = myList. get ( i) ;
System . out. println ( obj) ;
}
}
}
2.1.7 ArrayList
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. List ;
public class ArrayListTest01 {
public static void main ( String [ ] args) {
List list1 = new ArrayList ( ) ;
System . out. println ( list1. size ( ) ) ;
List list2 = new ArrayList ( 20 ) ;
System . out. println ( list2. size ( ) ) ;
list1. add ( 1 ) ;
list1. add ( 2 ) ;
list1. add ( 3 ) ;
list1. add ( 4 ) ;
list1. add ( 5 ) ;
list1. add ( 6 ) ;
list1. add ( 7 ) ;
list1. add ( 8 ) ;
list1. add ( 9 ) ;
list1. add ( 10 ) ;
System . out. println ( list1. size ( ) ) ;
list1. add ( 11 ) ;
System . out. println ( list1. size ( ) ) ;
}
}
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Collection ;
import java. util. HashSet ;
import java. util. List ;
public class ArrayListTest02 {
public static void main ( String [ ] args) {
List myList1 = new ArrayList ( ) ;
List myList2 = new ArrayList ( 100 ) ;
Collection c = new HashSet ( ) ;
c. add ( 100 ) ;
c. add ( 200 ) ;
c. add ( 900 ) ;
c. add ( 50 ) ;
List myList3 = new ArrayList ( c) ;
for ( int i = 0 ; i < myList3. size ( ) ; i++ ) {
System . out. println ( myList3. get ( i) ) ;
}
}
}
2.1.8 Vector
package com. yxj. javase. collection ;
import java. util. * ;
public class VectorTest {
public static void main ( String [ ] args) {
List vector = new Vector ( ) ;
vector. add ( 1 ) ;
vector. add ( 2 ) ;
vector. add ( 3 ) ;
vector. add ( 4 ) ;
vector. add ( 5 ) ;
vector. add ( 6 ) ;
vector. add ( 7 ) ;
vector. add ( 8 ) ;
vector. add ( 9 ) ;
vector. add ( 10 ) ;
vector. add ( 11 ) ;
Iterator it = vector. iterator ( ) ;
while ( it. hasNext ( ) ) {
Object obj = it. next ( ) ;
System . out. println ( obj) ;
}
List myList = new ArrayList ( ) ;
Collections . synchronizedList ( myList) ;
myList. add ( "111" ) ;
myList. add ( "222" ) ;
myList. add ( "333" ) ;
}
}
2.1.9 泛型
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Iterator ;
import java. util. List ;
public class GenericTest01 {
public static void main ( String [ ] args) {
List < Animal > myList = new ArrayList < Animal > ( ) ;
Cat c = new Cat ( ) ;
Bird b = new Bird ( ) ;
myList. add ( c) ;
myList. add ( b) ;
Iterator < Animal > it = myList. iterator ( ) ;
while ( it. hasNext ( ) ) {
Animal a = it. next ( ) ;
if ( a instanceof Cat ) {
Cat x = ( Cat ) a;
x. catchMouse ( ) ;
}
if ( a instanceof Bird ) {
Bird y = ( Bird ) a;
y. fly ( ) ;
}
}
}
}
class Animal {
public void move ( ) {
System . out. println ( "动物在移动!" ) ;
}
}
class Cat extends Animal {
public void catchMouse ( ) {
System . out. println ( "猫抓老鼠!" ) ;
}
}
class Bird extends Animal {
public void fly ( ) {
System . out. println ( "鸟儿在飞翔!" ) ;
}
}
2.1.9.1 钻石表达式
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Iterator ;
import java. util. List ;
public class GenericTest02 {
public static void main ( String [ ] args) {
List < Animal > myList = new ArrayList < > ( ) ;
myList. add ( new Animal ( ) ) ;
myList. add ( new Cat ( ) ) ;
myList. add ( new Bird ( ) ) ;
Iterator < Animal > it = myList. iterator ( ) ;
while ( it. hasNext ( ) ) {
Animal a = it. next ( ) ;
a. move ( ) ;
}
List < String > strList = new ArrayList < > ( ) ;
strList. add ( "http://www.126.com" ) ;
strList. add ( "http://www.baidu.com" ) ;
strList. add ( "http://www.yxj.com" ) ;
Iterator < String > it2 = strList. iterator ( ) ;
while ( it2. hasNext ( ) ) {
String s = it2. next ( ) ;
String newString = s. substring ( 7 ) ;
System . out. println ( newString) ;
}
}
}
2.1.9.2 自定义泛型
package com. yxj. javase. collection ;
public class GenericTest03 < 标识符随便写> {
public void doSome ( 标识符随便写 o) {
System . out. println ( o) ;
}
public static void main ( String [ ] args) {
GenericTest03 < String > gt = new GenericTest03 < > ( ) ;
gt. doSome ( "abc" ) ;
GenericTest03 < Integer > gt2 = new GenericTest03 < > ( ) ;
gt2. doSome ( 100 ) ;
MyIterator < String > mi = new MyIterator < > ( ) ;
String s1 = mi. get ( ) ;
MyIterator < Animal > mi2 = new MyIterator < > ( ) ;
Animal a = mi2. get ( ) ;
}
}
class MyIterator < T > {
public T get ( ) {
return null ;
}
}
2.1.10 增强for循环
package com. yxj. javase. collection ;
import java. util. ArrayList ;
import java. util. Iterator ;
import java. util. List ;
public class ForEachTest02 {
public static void main ( String [ ] args) {
List < String > strList = new ArrayList < > ( ) ;
strList. add ( "hello" ) ;
strList. add ( "world!" ) ;
strList. add ( "kitty!" ) ;
Iterator < String > it = strList. iterator ( ) ;
while ( it. hasNext ( ) ) {
String s = it. next ( ) ;
System . out. println ( s) ;
}
for ( int i = 0 ; i < strList. size ( ) ; i++ ) {
System . out. println ( strList. get ( i) ) ;
}
for ( String s : strList) {
System . out. println ( s) ;
}
List < Integer > list = new ArrayList < > ( ) ;
list. add ( 100 ) ;
list. add ( 200 ) ;
list. add ( 300 ) ;
for ( Integer i : list) {
System . out. println ( i) ;
}
}
}
2.1.11 HashSet
package com. yxj. javase. collection ;
import java. util. HashSet ;
import java. util. Set ;
public class HashSetTest01 {
public static void main ( String [ ] args) {
Set < String > strs = new HashSet < > ( ) ;
strs. add ( "hello3" ) ;
strs. add ( "hello4" ) ;
strs. add ( "hello1" ) ;
strs. add ( "hello2" ) ;
strs. add ( "hello3" ) ;
strs. add ( "hello3" ) ;
strs. add ( "hello3" ) ;
strs. add ( "hello3" ) ;
for ( String s : strs) {
System . out. println ( s) ;
}
}
}
2.1.12 TreeSet
package com. yxj. javase. collection ;
import java. util. Set ;
import java. util. TreeSet ;
public class TreeSetTest01 {
public static void main ( String [ ] args) {
Set < String > strs = new TreeSet < > ( ) ;
strs. add ( "A" ) ;
strs. add ( "B" ) ;
strs. add ( "Z" ) ;
strs. add ( "Y" ) ;
strs. add ( "Z" ) ;
strs. add ( "K" ) ;
strs. add ( "M" ) ;
for ( String s : strs) {
System . out. println ( s) ;
}
}
}
package com. yxj. javase. collection ;
import java. util. TreeSet ;
public class TreeSetTest04 {
public static void main ( String [ ] args) {
Customer c1 = new Customer ( 32 ) ;
Customer c2 = new Customer ( 20 ) ;
Customer c3 = new Customer ( 30 ) ;
Customer c4 = new Customer ( 25 ) ;
TreeSet < Customer > customers = new TreeSet < > ( ) ;
customers. add ( c1) ;
customers. add ( c2) ;
customers. add ( c3) ;
customers. add ( c4) ;
for ( Customer c : customers) {
System . out. println ( c) ;
}
}
}
class Customer implements Comparable < Customer > {
int age;
public Customer ( int age) {
this . age = age;
}
@Override
public int compareTo ( Customer c) {
return c. age - this . age;
}
public String toString ( ) {
return "Customer[age=" + age+ "]" ;
}
}
package com. yxj. javase. collection ;
import java. util. Comparator ;
import java. util. TreeSet ;
public class TreeSetTest06 {
public static void main ( String [ ] args) {
TreeSet < WuGui > wuGuis = new TreeSet < > ( new Comparator < WuGui > ( ) {
@Override
public int compare ( WuGui o1, WuGui o2) {
return o1. age - o2. age;
}
} ) ;
wuGuis. add ( new WuGui ( 1000 ) ) ;
wuGuis. add ( new WuGui ( 800 ) ) ;
wuGuis. add ( new WuGui ( 810 ) ) ;
for ( WuGui wuGui : wuGuis) {
System . out. println ( wuGui) ;
}
}
}
class WuGui {
int age;
public WuGui ( int age) {
this . age = age;
}
@Override
public String toString ( ) {
return "小乌龟[" +
"age=" + age +
']' ;
}
}
CollectionsTest
package com. yxj. javase. collection ;
import java. util. * ;
public class CollectionsTest {
public static void main ( String [ ] args) {
List < String > list = new ArrayList < > ( ) ;
Collections . synchronizedList ( list) ;
list. add ( "abf" ) ;
list. add ( "abx" ) ;
list. add ( "abc" ) ;
list. add ( "abe" ) ;
Collections . sort ( list) ;
for ( String s : list) {
System . out. println ( s) ;
}
List < WuGui2 > wuGuis = new ArrayList < > ( ) ;
wuGuis. add ( new WuGui2 ( 1000 ) ) ;
wuGuis. add ( new WuGui2 ( 8000 ) ) ;
wuGuis. add ( new WuGui2 ( 500 ) ) ;
Collections . sort ( wuGuis) ;
for ( WuGui2 wg : wuGuis) {
System . out. println ( wg) ;
}
Set < String > set = new HashSet < > ( ) ;
set. add ( "king" ) ;
set. add ( "kingsoft" ) ;
set. add ( "king2" ) ;
set. add ( "king1" ) ;
List < String > myList = new ArrayList < > ( set) ;
Collections . sort ( myList) ;
for ( String s : myList) {
System . out. println ( s) ;
}
}
}
class WuGui2 implements Comparable < WuGui2 > {
int age;
public WuGui2 ( int age) {
this . age = age;
}
@Override
public int compareTo ( WuGui2 o) {
return this . age - o. age;
}
@Override
public String toString ( ) {
return "WuGui2{" +
"age=" + age +
'}' ;
}
}
2.1.13 Map接口中常用方法
package com. yxj. javase. collection ;
import java. util. Collection ;
import java. util. HashMap ;
import java. util. Map ;
public class MapTest01 {
public static void main ( String [ ] args) {
Map < Integer , String > map = new HashMap < > ( ) ;
map. put ( 1 , "zhangsan" ) ;
map. put ( 2 , "lisi" ) ;
map. put ( 3 , "wangwu" ) ;
map. put ( 4 , "zhaoliu" ) ;
String value = map. get ( 2 ) ;
System . out. println ( value) ;
System . out. println ( "键值对的数量:" + map. size ( ) ) ;
map. remove ( 2 ) ;
System . out. println ( "键值对的数量:" + map. size ( ) ) ;
System . out. println ( map. containsKey ( new Integer ( 4 ) ) ) ;
System . out. println ( map. containsValue ( new String ( "wangwu" ) ) ) ;
Collection < String > values = map. values ( ) ;
for ( String s : values) {
System . out. println ( s) ;
}
map. clear ( ) ;
System . out. println ( "键值对的数量:" + map. size ( ) ) ;
System . out. println ( map. isEmpty ( ) ) ;
}
}
2.1.13.1 Map集合的遍历。【非常重要】
package com. yxj. javase. collection ;
import java. util. HashMap ;
import java. util. Iterator ;
import java. util. Map ;
import java. util. Set ;
public class MapTest02 {
public static void main ( String [ ] args) {
Map < Integer , String > map = new HashMap < > ( ) ;
map. put ( 1 , "zhangsan" ) ;
map. put ( 2 , "lisi" ) ;
map. put ( 3 , "wangwu" ) ;
map. put ( 4 , "zhaoliu" ) ;
Set < Integer > keys = map. keySet ( ) ;
for ( Integer key : keys) {
System . out. println ( key + "=" + map. get ( key) ) ;
}
Set < Map. Entry < Integer , String > > set = map. entrySet ( ) ;
for ( Map. Entry < Integer , String > node : set) {
System . out. println ( node. getKey ( ) + "--->" + node. getValue ( ) ) ;
}
}
}
package com. yxj. javase. collection ;
import java. util. HashMap ;
import java. util. Map ;
import java. util. Set ;
public class HashMapTest01 {
public static void main ( String [ ] args) {
Map < Integer , String > map = new HashMap < > ( ) ;
map. put ( 1111 , "zhangsan" ) ;
map. put ( 6666 , "lisi" ) ;
map. put ( 7777 , "wangwu" ) ;
map. put ( 2222 , "zhaoliu" ) ;
map. put ( 2222 , "king" ) ;
System . out. println ( map. size ( ) ) ;
Set < Map. Entry < Integer , String > > set = map. entrySet ( ) ;
for ( Map. Entry < Integer , String > entry : set) {
System . out. println ( entry. getKey ( ) + "=" + entry. getValue ( ) ) ;
}
}
}
2.1.13.2 Hashtable
package com. yxj. javase. bean ;
import java. util. Hashtable ;
import java. util. Map ;
public class HashtableTest01 {
public static void main ( String [ ] args) {
Map map = new Hashtable ( ) ;
map. put ( 100 , null ) ;
}
}
2.1.13.3 Properties
package com. yxj. javase. collection ;
import java. util. Properties ;
public class PropertiesTest01 {
public static void main ( String [ ] args) {
Properties pro = new Properties ( ) ;
pro. setProperty ( "url" , "jdbc:mysql://localhost:3306/yxj" ) ;
pro. setProperty ( "driver" , "com.mysql.jdbc.Driver" ) ;
pro. setProperty ( "username" , "root" ) ;
pro. setProperty ( "password" , "123" ) ;
String url = pro. getProperty ( "url" ) ;
String driver = pro. getProperty ( "driver" ) ;
String username = pro. getProperty ( "username" ) ;
String password = pro. getProperty ( "password" ) ;
System . out. println ( url) ;
System . out. println ( driver) ;
System . out. println ( username) ;
System . out. println ( password) ;
}
}
2.1.13.4 集合大总结
package com. yxj. javase. review ;
import java. util. ArrayList ;
import java. util. Iterator ;
import java. util. LinkedList ;
public class ArrayListTest {
public static void main ( String [ ] args) {
LinkedList < String > list = new LinkedList < > ( ) ;
list. add ( "zhangsan" ) ;
list. add ( "lisi" ) ;
list. add ( "wangwu" ) ;
String firstElt = list. get ( 0 ) ;
System . out. println ( firstElt) ;
for ( int i = 0 ; i < list. size ( ) ; i++ ) {
String elt = list. get ( i) ;
System . out. println ( elt) ;
}
Iterator < String > it = list. iterator ( ) ;
while ( it. hasNext ( ) ) {
System . out. println ( it. next ( ) ) ;
}
for ( String s : list) {
System . out. println ( s) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. javase. review ;
import java. util. HashSet ;
import java. util. Iterator ;
import java. util. Objects ;
import java. util. Set ;
public class HashSetTest {
public static void main ( String [ ] args) {
HashSet < String > set = new HashSet < > ( ) ;
set. add ( "abc" ) ;
set. add ( "def" ) ;
set. add ( "king" ) ;
Iterator < String > it = set. iterator ( ) ;
while ( it. hasNext ( ) ) {
System . out. println ( it. next ( ) ) ;
}
for ( String s : set) {
System . out. println ( s) ;
}
set. add ( "king" ) ;
set. add ( "king" ) ;
set. add ( "king" ) ;
System . out. println ( set. size ( ) ) ;
set. add ( "1" ) ;
set. add ( "10" ) ;
set. add ( "2" ) ;
for ( String s : set) {
System . out. println ( "--->" + s) ;
}
Set < Student > students = new HashSet < > ( ) ;
Student s1 = new Student ( 111 , "zhangsan" ) ;
Student s2 = new Student ( 222 , "lisi" ) ;
Student s3 = new Student ( 111 , "zhangsan" ) ;
students. add ( s1) ;
students. add ( s2) ;
students. add ( s3) ;
System . out. println ( students. size ( ) ) ;
for ( Student stu : students) {
System . out. println ( stu) ;
}
}
}
class Student {
int no;
String name;
public Student ( ) {
}
public Student ( int no, String name) {
this . no = no;
this . name = name;
}
@Override
public String toString ( ) {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
'}' ;
}
@Override
public boolean equals ( Object o) {
if ( this == o) return true ;
if ( o == null || getClass ( ) != o. getClass ( ) ) return false ;
Student student = ( Student ) o;
return no == student. no &&
Objects . equals ( name, student. name) ;
}
@Override
public int hashCode ( ) {
return Objects . hash ( no, name) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. javase. review ;
import java. util. Comparator ;
import java. util. Iterator ;
import java. util. TreeSet ;
public class TreeSetTest {
public static void main ( String [ ] args) {
TreeSet < Integer > ts = new TreeSet < > ( new Comparator < Integer > ( ) {
@Override
public int compare ( Integer o1, Integer o2) {
return o2 - o1;
}
} ) ;
ts. add ( 1 ) ;
ts. add ( 100 ) ;
ts. add ( 10 ) ;
ts. add ( 10 ) ;
ts. add ( 10 ) ;
ts. add ( 10 ) ;
ts. add ( 0 ) ;
Iterator < Integer > it = ts. iterator ( ) ;
while ( it. hasNext ( ) ) {
Integer i = it. next ( ) ;
System . out. println ( i) ;
}
for ( Integer x : ts) {
System . out. println ( x) ;
}
TreeSet < A > atree = new TreeSet < > ( ) ;
atree. add ( new A ( 100 ) ) ;
atree. add ( new A ( 200 ) ) ;
atree. add ( new A ( 500 ) ) ;
atree. add ( new A ( 300 ) ) ;
atree. add ( new A ( 400 ) ) ;
atree. add ( new A ( 1000 ) ) ;
for ( A a : atree) {
System . out. println ( a) ;
}
TreeSet < B > btree = new TreeSet < > ( new Comparator < B > ( ) {
@Override
public int compare ( B o1, B o2) {
return o1. i - o2. i;
}
} ) ;
btree. add ( new B ( 500 ) ) ;
btree. add ( new B ( 100 ) ) ;
btree. add ( new B ( 200 ) ) ;
btree. add ( new B ( 600 ) ) ;
btree. add ( new B ( 300 ) ) ;
btree. add ( new B ( 50 ) ) ;
for ( B b : btree) {
System . out. println ( b) ;
}
}
}
class A implements Comparable < A > {
int i;
public A ( int i) {
this . i = i;
}
@Override
public String toString ( ) {
return "A{" +
"i=" + i +
'}' ;
}
@Override
public int compareTo ( A o) {
return o. i - this . i;
}
}
class B {
int i;
public B ( int i) {
this . i = i;
}
@Override
public String toString ( ) {
return "B{" +
"i=" + i +
'}' ;
}
}
class BComparator implements Comparator < B > {
@Override
public int compare ( B o1, B o2) {
return o1. i - o2. i;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. javase. review ;
import java. util. HashMap ;
import java. util. Map ;
import java. util. Set ;
public class HashMapTest {
public static void main ( String [ ] args) {
Map < Integer , String > map = new HashMap < > ( ) ;
map. put ( 1 , "zhangsan" ) ;
map. put ( 9 , "lisi" ) ;
map. put ( 10 , "wangwu" ) ;
map. put ( 2 , "king" ) ;
map. put ( 2 , "simth" ) ;
System . out. println ( map. size ( ) ) ;
System . out. println ( map. get ( 2 ) ) ;
Set < Integer > keys = map. keySet ( ) ;
for ( Integer key : keys) {
System . out. println ( key + "=" + map. get ( key) ) ;
}
Set < Map. Entry < Integer , String > > nodes = map. entrySet ( ) ;
for ( Map. Entry < Integer , String > node : nodes) {
System . out. println ( node. getKey ( ) + "=" + node. getValue ( ) ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. javase. review ;
import java. util. Properties ;
public class PropertiesTest {
public static void main ( String [ ] args) {
Properties pro = new Properties ( ) ;
pro. setProperty ( "username" , "test" ) ;
pro. setProperty ( "password" , "test123" ) ;
String username = pro. getProperty ( "username" ) ;
String password = pro. getProperty ( "password" ) ;
System . out. println ( username) ;
System . out. println ( password) ;
}
}
2.1.13.5 总结(集合所有的实现类)
ArrayList:底层是数组。
LinkedList:底层是双向链表。
Vector:底层是数组,线程安全的,效率较低,使用较少。
HashSet:底层是 HashMap,放到 HashSet集合中的元素
等同于放到 Hash Map集合key部分了
TreeSet:底层是 TreeMap,放到 TreeSet集合中的元素等同于
放到 TreeMap集合key部分了。
HashMap:底层是哈希表。
Hashtable:底层也是哈希表,只不过线程安全的,效
率较低,使用较少。
Properties:是线程安全的,并且key和 value只能存储
字符串 String.
TreeMap:底层是二叉树。 TreeMap集合的key可以自动
按照大小顺序排序。
List集合存储元素的特点:
有序可重复
有序:存进去的顺序和取出的顺序相同,每一个元素都有下标。
可重复:存进去1,可以再存储一个1
Set(Map)集合存储元素的特点:
无序不可重复
无序:存进去的顺序和取出的顺序不一定相同。另外Set集
合中元素没有下标。
不可重复:存进去1,不能再存储1了。
SortedSet( SortedMap)集合存储元素特点:
首先是无序不可重复的,但是 SortedSet集合中的元素是
可排序的。“
无序:存进去的顺序和取出的顺序不一定相同。另外set集合中
元素没有下标
不可重复:存进去1,不能再存储1了。
可排序:可以按照大小顺序排列。
Map集合的key,就是一个Set集合。
往Set集合中放效据,实际上放到了Map集合的key部分。
3.1 IO流
InputStream和OutputStream继承结构图
InputStream和OutputStream继承结构图
IO流的分类?
有多种分类方式:
一种方式是按照流的方向进行分类:
以内存作为参照物,
往内存中去,叫做输入(Input)。或者叫做读(Read)。
从内存中出来,叫做输出(Output)。或者叫做写(Write)。
另一种方式是按照读取数据方式不同进行分类:
有的流是按照字节的方式读取数据,一次读取1个字节byte,等
同于一次读取8个二进制位。
这种流是万能的,什么类型的文件都可以读取。包
括:文本文件,图片,声音文件,视频文件等....
假设文件file1.txt,采用字节流的话是这样读的:
a中国bc张三fe
第一次读:一个字节,正好读到'a'
第二次读:一个字节,正好读到'中'字符的一半。
第三次读:一个字节,正好读到'中'字符的另外一半。
有的流是按照字符的方式读取数据的,一次读取一个字符,
这种流是为了方便读取
普通文本文件而存在的,这种流不能读取:图片、声音、视
频等文件。只能读取纯
文本文件,连word文件都无法读取。
假设文件file1.txt,采用字符流的话是这样读的:
a中国bc张三fe
第一次读:'a'字符('a'字符在windows系统中占用1个字节。)
第二次读:'中'字符('中'字符在windows系统中占用2个字节。)
综上所述:流的分类
输入流、输出流
字节流、字符流
java IO流这块有四大家族:
四大家族的首领:
java.io.InputStream 字节输入流
java.io.OutputStream 字节输出流
java.io.Reader 字符输入流
java.io.Writer 字符输出流
四大家族的首领都是抽象类。(abstract class)
所有的流都实现了:
java.io.Closeable接口,都是可关闭的,都有close()方法。
流毕竟是一个管道,这个是内存和硬盘之间的通道,用完之
后一定要关闭,
不然会耗费(占用)很多资源。养成好习惯,用完流一定要关闭。
所有的输出流都实现了:
java.io.Flushable接口,都是可刷新的,都有flush()方法。
养成一个好习惯,输出流在最终输出之后,一定要记得flush()
刷新一下。这个刷新表示将通道/管道当中剩余未输出的数据
强行输出完(清空管道!)刷新的作用就是清空管道。
注意:如果没有flush()可能会导致丢失数据。
注意:在java中只要“类名”以Stream结尾的都是字节
流。以“Reader/Writer”结尾的都是字符流。
java.io包下需要掌握的流有16个:
文件专属:
java.io.FileInputStream(掌握)
java.io.FileOutputStream(掌握)
java.io.FileReader
java.io.FileWriter
转换流:(将字节流转换成字符流)
java.io.InputStreamReader
java.io.OutputStreamWriter
缓冲流专属:
java.io.BufferedReader
java.io.BufferedWriter
java.io.BufferedInputStream
java.io.BufferedOutputStream
数据流专属:
java.io.DataInputStream
java.io.DataOutputStream
标准输出流:
java.io.PrintWriter
java.io.PrintStream(掌握)
对象专属流:
java.io.ObjectInputStream(掌握)
java.io.ObjectOutputStream(掌握)
java.io.File类。
File类的常用方法。
8、java io这块还剩下什么内容:
第一:ObjectInputStream ObjectOutputStream的使用。
第二:IO流+Properties集合的联合使用。
2、关于对象流
ObjectInputStream
ObjectOutputStream
重点:
参与序列化的类型必须实现java.io.Serializable接口。
并且建议将序列化版本号手动的写出来。
private static final long serialVersionUID = 1L;
3、IO + Properties联合使用。
IO流:文件的读和写。
Properties:是一个Map集合,key和value都是String类型。
3.1.1 FileInputStream
package com. yxj. java. io ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
public class FileInputStreamTest01 {
public static void main ( String [ ] args) {
FileInputStream fis = null ;
try {
fis = new FileInputStream ( "D:/course/JavaProjects/02-JavaSE/temp" ) ;
int readData = fis. read ( ) ;
System . out. println ( readData) ;
readData = fis. read ( ) ;
System . out. println ( readData) ;
readData = fis. read ( ) ;
System . out. println ( readData) ;
readData = fis. read ( ) ;
System . out. println ( readData) ;
readData = fis. read ( ) ;
System . out. println ( readData) ;
readData = fis. read ( ) ;
System . out. println ( readData) ;
readData = fis. read ( ) ;
System . out. println ( readData) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fis != null ) {
try {
fis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
package com. yxj. java. io ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
public class FileInputStreamTest03 {
public static void main ( String [ ] args) {
FileInputStream fis = null ;
try {
fis = new FileInputStream ( "chapter23/src/com/yxj/java/io/tempfile4" ) ;
byte [ ] bytes = new byte [ 4 ] ;
int readCount = fis. read ( bytes) ;
System . out. println ( readCount) ;
System . out. println ( new String ( bytes, 0 , readCount) ) ;
readCount = fis. read ( bytes) ;
System . out. println ( readCount) ;
System . out. println ( new String ( bytes, 0 , readCount) ) ;
readCount = fis. read ( bytes) ;
System . out. println ( readCount) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fis != null ) {
try {
fis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
package com. yxj. java. io ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
public class FileInputStreamTest04 {
public static void main ( String [ ] args) {
FileInputStream fis = null ;
try {
fis = new FileInputStream ( "chapter23/src/tempfile3" ) ;
byte [ ] bytes = new byte [ 4 ] ;
int readCount = 0 ;
while ( ( readCount = fis. read ( bytes) ) != - 1 ) {
System . out. print ( new String ( bytes, 0 , readCount) ) ;
}
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fis != null ) {
try {
fis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
package com. yxj. java. io ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. IOException ;
public class FileInputStreamTest05 {
public static void main ( String [ ] args) {
FileInputStream fis = null ;
try {
fis = new FileInputStream ( "tempfile" ) ;
System . out. println ( "总字节数量:" + fis. available ( ) ) ;
fis. skip ( 3 ) ;
System . out. println ( fis. read ( ) ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fis != null ) {
try {
fis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
3.1.2 FileOutputStream
package com. yxj. java. io ;
import java. io. FileNotFoundException ;
import java. io. FileOutputStream ;
import java. io. IOException ;
public class FileOutputStreamTest01 {
public static void main ( String [ ] args) {
FileOutputStream fos = null ;
try {
fos = new FileOutputStream ( "chapter23/src/tempfile3" , true ) ;
byte [ ] bytes = { 97 , 98 , 99 , 100 } ;
fos. write ( bytes) ;
fos. write ( bytes, 0 , 2 ) ;
String s = "我是一个中国人,我骄傲!!!" ;
byte [ ] bs = s. getBytes ( ) ;
fos. write ( bs) ;
fos. flush ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fos != null ) {
try {
fos. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
copy
package com. yxj. java. io ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. FileOutputStream ;
import java. io. IOException ;
public class Copy01 {
public static void main ( String [ ] args) {
FileInputStream fis = null ;
FileOutputStream fos = null ;
try {
fis = new FileInputStream ( "D:\\course\\02-JavaSE\\video\\chapter01\\动力节点-JavaSE-杜聚宾-001-文件扩展名的显示.avi" ) ;
fos = new FileOutputStream ( "C:\\动力节点-JavaSE-杜聚宾-001-文件扩展名的显示.avi" ) ;
byte [ ] bytes = new byte [ 1024 * 1024 ] ;
int readCount = 0 ;
while ( ( readCount = fis. read ( bytes) ) != - 1 ) {
fos. write ( bytes, 0 , readCount) ;
}
fos. flush ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fos != null ) {
try {
fos. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
if ( fis != null ) {
try {
fis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
3.1.3 FileReader
package com. yxj. java. io ;
import java. io. FileNotFoundException ;
import java. io. FileReader ;
import java. io. IOException ;
public class FileReaderTest {
public static void main ( String [ ] args) {
FileReader reader = null ;
try {
reader = new FileReader ( "tempfile" ) ;
char [ ] chars = new char [ 4 ] ;
reader. read ( chars) ;
for ( char c : chars) {
System . out. println ( c) ;
}
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( reader != null ) {
try {
reader. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
3.1.4 FileWriter
package com. yxj. java. io ;
import java. io. FileWriter ;
import java. io. IOException ;
public class FileWriterTest {
public static void main ( String [ ] args) {
FileWriter out = null ;
try {
out = new FileWriter ( "file" , true ) ;
char [ ] chars = { '我' , '是' , '中' , '国' , '人' } ;
out. write ( chars) ;
out. write ( chars, 2 , 3 ) ;
out. write ( "我是一名java软件工程师!" ) ;
out. write ( "\n" ) ;
out. write ( "hello world!" ) ;
out. flush ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( out != null ) {
try {
out. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
Copy02
package com. yxj. java. io ;
import java. io. FileNotFoundException ;
import java. io. FileReader ;
import java. io. FileWriter ;
import java. io. IOException ;
public class Copy02 {
public static void main ( String [ ] args) {
FileReader in = null ;
FileWriter out = null ;
try {
in = new FileReader ( "chapter23/src/com/yxj/java/io/Copy02.java" ) ;
out = new FileWriter ( "Copy02.java" ) ;
char [ ] chars = new char [ 1024 * 512 ] ;
int readCount = 0 ;
while ( ( readCount = in. read ( chars) ) != - 1 ) {
out. write ( chars, 0 , readCount) ;
}
out. flush ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( in != null ) {
try {
in. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
if ( out != null ) {
try {
out. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
3.1.5 BufferedReader
package com. yxj. java. io ;
import java. io. BufferedReader ;
import java. io. FileReader ;
public class BufferedReaderTest01 {
public static void main ( String [ ] args) throws Exception {
FileReader reader = new FileReader ( "Copy02.java" ) ;
BufferedReader br = new BufferedReader ( reader) ;
String s = null ;
while ( ( s = br. readLine ( ) ) != null ) {
System . out. print ( s) ;
}
br. close ( ) ;
}
}
package com. yxj. java. io ;
import java. io. BufferedReader ;
import java. io. FileInputStream ;
import java. io. InputStream ;
import java. io. InputStreamReader ;
public class BufferedReaderTest02 {
public static void main ( String [ ] args) throws Exception {
BufferedReader br = new BufferedReader ( new InputStreamReader ( new FileInputStream ( "Copy02.java" ) ) ) ;
String line = null ;
while ( ( line = br. readLine ( ) ) != null ) {
System . out. println ( line) ;
}
br. close ( ) ;
}
}
3.1.6 BufferWriter
package com. yxj. java. io ;
import java. io. BufferedWriter ;
import java. io. FileOutputStream ;
import java. io. FileWriter ;
import java. io. OutputStreamWriter ;
public class BufferedWriterTest {
public static void main ( String [ ] args) throws Exception {
BufferedWriter out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( "copy" , true ) ) ) ;
out. write ( "hello world!" ) ;
out. write ( "\n" ) ;
out. write ( "hello kitty!" ) ;
out. flush ( ) ;
out. close ( ) ;
}
}
3.1.7 DataInputStream
package com. yxj. java. io ;
import java. io. DataInputStream ;
import java. io. FileInputStream ;
public class DataInputStreamTest01 {
public static void main ( String [ ] args) throws Exception {
DataInputStream dis = new DataInputStream ( new FileInputStream ( "data" ) ) ;
byte b = dis. readByte ( ) ;
short s = dis. readShort ( ) ;
int i = dis. readInt ( ) ;
long l = dis. readLong ( ) ;
float f = dis. readFloat ( ) ;
double d = dis. readDouble ( ) ;
boolean sex = dis. readBoolean ( ) ;
char c = dis. readChar ( ) ;
System . out. println ( b) ;
System . out. println ( s) ;
System . out. println ( i + 1000 ) ;
System . out. println ( l) ;
System . out. println ( f) ;
System . out. println ( d) ;
System . out. println ( sex) ;
System . out. println ( c) ;
dis. close ( ) ;
}
}
3.1.8 DataOutputStream
package com. yxj. java. io ;
import java. io. DataOutputStream ;
import java. io. FileOutputStream ;
public class DataOutputStreamTest {
public static void main ( String [ ] args) throws Exception {
DataOutputStream dos = new DataOutputStream ( new FileOutputStream ( "data" ) ) ;
byte b = 100 ;
short s = 200 ;
int i = 300 ;
long l = 400L ;
float f = 3.0F ;
double d = 3.14 ;
boolean sex = false ;
char c = 'a' ;
dos. writeByte ( b) ;
dos. writeShort ( s) ;
dos. writeInt ( i) ;
dos. writeLong ( l) ;
dos. writeFloat ( f) ;
dos. writeDouble ( d) ;
dos. writeBoolean ( sex) ;
dos. writeChar ( c) ;
dos. flush ( ) ;
dos. close ( ) ;
}
}
3.1.9 PrintStream
package com. yxj. java. io ;
import java. io. FileOutputStream ;
import java. io. PrintStream ;
public class PrintStreamTest {
public static void main ( String [ ] args) throws Exception {
System . out. println ( "hello world!" ) ;
PrintStream ps = System . out;
ps. println ( "hello zhangsan" ) ;
ps. println ( "hello lisi" ) ;
ps. println ( "hello wangwu" ) ;
PrintStream printStream = new PrintStream ( new FileOutputStream ( "log" ) ) ;
System . setOut ( printStream) ;
System . out. println ( "hello world" ) ;
System . out. println ( "hello kitty" ) ;
System . out. println ( "hello zhangsan" ) ;
}
}
3.1.10 日志工具
package com. yxj. java. io ;
import java. io. FileNotFoundException ;
import java. io. FileOutputStream ;
import java. io. PrintStream ;
import java. text. SimpleDateFormat ;
import java. util. Date ;
public class Logger {
public static void log ( String msg) {
try {
PrintStream out = new PrintStream ( new FileOutputStream ( "log.txt" , true ) ) ;
System . setOut ( out) ;
Date nowTime = new Date ( ) ;
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss SSS" ) ;
String strTime = sdf. format ( nowTime) ;
System . out. println ( strTime + ": " + msg) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
}
}
}
package com. yxj. java. io ;
public class LogTest {
public static void main ( String [ ] args) {
Logger . log ( "调用了System类的gc()方法,建议启动垃圾回收" ) ;
Logger . log ( "调用了UserService的doSome()方法" ) ;
Logger . log ( "用户尝试进行登录,验证失败" ) ;
Logger . log ( "我非常喜欢这个记录日志的工具哦!" ) ;
}
}
3.1.11 File
package com. yxj. java. io ;
import java. io. File ;
public class FileTest01 {
public static void main ( String [ ] args) throws Exception {
File f1 = new File ( "D:\\file" ) ;
System . out. println ( f1. exists ( ) ) ;
File f2 = new File ( "D:/a/b/c/d/e/f" ) ;
File f3 = new File ( "D:\\course\\01-开课\\学习方法.txt" ) ;
String parentPath = f3. getParent ( ) ;
System . out. println ( parentPath) ;
File parentFile = f3. getParentFile ( ) ;
System . out. println ( "获取绝对路径:" + parentFile. getAbsolutePath ( ) ) ;
File f4 = new File ( "copy" ) ;
System . out. println ( "绝对路径:" + f4. getAbsolutePath ( ) ) ;
}
}
package com. yxj. java. io ;
import java. io. File ;
import java. text. SimpleDateFormat ;
import java. util. Date ;
public class FileTest02 {
public static void main ( String [ ] args) {
File f1 = new File ( "D:\\course\\01-开课\\开学典礼.ppt" ) ;
System . out. println ( "文件名:" + f1. getName ( ) ) ;
System . out. println ( f1. isDirectory ( ) ) ;
System . out. println ( f1. isFile ( ) ) ;
long haoMiao = f1. lastModified ( ) ;
Date time = new Date ( haoMiao) ;
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss SSS" ) ;
String strTime = sdf. format ( time) ;
System . out. println ( strTime) ;
System . out. println ( f1. length ( ) ) ;
}
}
package com. yxj. java. io ;
import java. io. File ;
public class FileTest03 {
public static void main ( String [ ] args) {
File f = new File ( "D:\\course\\01-开课" ) ;
File [ ] files = f. listFiles ( ) ;
for ( File file : files) {
System . out. println ( file. getName ( ) ) ;
}
}
}
3.1.12 序列化
ObjectOutputStreamTest01
package com. yxj. java. io ;
import com. yxj. java. bean. Student ;
import java. io. FileOutputStream ;
import java. io. ObjectOutputStream ;
public class ObjectOutputStreamTest01 {
public static void main ( String [ ] args) throws Exception {
Student s = new Student ( 1111 , "zhangsan" ) ;
ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( "students" ) ) ;
oos. writeObject ( s) ;
oos. flush ( ) ;
oos. close ( ) ;
}
}
package com. yxj. java. bean ;
import java. io. Serializable ;
public class Student implements Serializable {
private static final long serialVersionUID = 1L ;
private int no;
private int age;
private String email;
private String address;
public Student ( ) {
}
public Student ( int no, String name) {
this . no = no;
}
public int getNo ( ) {
return no;
}
public void setNo ( int no) {
this . no = no;
}
@Override
public String toString ( ) {
return "Student{" +
"no=" + no +
", age=" + age +
", email='" + email + '\'' +
", address='" + address + '\'' +
'}' ;
}
}
3.1.13 反序列化
package com. yxj. java. io ;
import com. yxj. java. bean. User ;
import java. io. FileInputStream ;
import java. io. ObjectInputStream ;
import java. util. List ;
public class ObjectInputStreamTest02 {
public static void main ( String [ ] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream ( new FileInputStream ( "users" ) ) ;
List < User > userList = ( List < User > ) ois. readObject ( ) ;
for ( User user : userList) {
System . out. println ( user) ;
}
ois. close ( ) ;
}
}
3.1.14 ObjectOutputStream
package com. yxj. java. io ;
import com. yxj. java. bean. Student ;
import java. io. FileOutputStream ;
import java. io. ObjectOutputStream ;
public class ObjectOutputStreamTest01 {
public static void main ( String [ ] args) throws Exception {
Student s = new Student ( 1111 , "zhangsan" ) ;
ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( "students" ) ) ;
oos. writeObject ( s) ;
oos. flush ( ) ;
oos. close ( ) ;
}
}
package com. yxj. java. io ;
import com. yxj. java. bean. User ;
import java. io. FileOutputStream ;
import java. io. ObjectOutputStream ;
import java. util. ArrayList ;
import java. util. List ;
public class ObjectOutputStreamTest02 {
public static void main ( String [ ] args) throws Exception {
List < User > userList = new ArrayList < > ( ) ;
userList. add ( new User ( 1 , "zhangsan" ) ) ;
userList. add ( new User ( 2 , "lisi" ) ) ;
userList. add ( new User ( 3 , "wangwu" ) ) ;
ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( "users" ) ) ;
oos. writeObject ( userList) ;
oos. flush ( ) ;
oos. close ( ) ;
}
}
IOPropertiesTest01 . java
package com. yxj. java. io ;
import java. io. FileReader ;
import java. util. Properties ;
public class IoPropertiesTest01 {
public static void main ( String [ ] args) throws Exception {
FileReader reader = new FileReader ( "chapter23/userinfo.properties" ) ;
Properties pro = new Properties ( ) ;
pro. load ( reader) ;
String username = pro. getProperty ( "username" ) ;
System . out. println ( username) ;
String password = pro. getProperty ( "password" ) ;
System . out. println ( password) ;
String data = pro. getProperty ( "data" ) ;
System . out. println ( data) ;
String usernamex = pro. getProperty ( "usernamex
") ;
System . out. println ( usernamex) ;
}
}
4.1 线程
1、关于线程的调度
1.1、常见的线程调度模型有哪些?
抢占式调度模型:
哪个线程的优先级比较高,抢到的CPU时间片的概率就高一些/多一些。
java采用的就是抢占式调度模型。
均分式调度模型:
平均分配CPU时间片。每个线程占有的CPU时间片时间长度一样。
平均分配,一切平等。
有一些编程语言,线程调度模型采用的是这种方式。
1.2、java中提供了哪些方法是和线程调度有关系的呢?
实例方法:
void setPriority(int newPriority) 设置线程的优先级
int getPriority() 获取线程优先级
最低优先级1
默认优先级是5
最高优先级10
优先级比较高的获取CPU时间片可能会多一些。(但也不完全是,大
概率是多的。)
静态方法:
static void yield() 让位方法
暂停当前正在执行的线程对象,并执行其他线程
yield()方法不是阻塞方法。让当前线程让位,让给其它线程使用。
yield()方法的执行会让当前线程从“运行状态”回到“就绪状态”。
注意:在回到就绪之后,有可能还会再次抢到。
实例方法:
void join()
合并线程
class MyThread1 extends Thread {
public void doSome(){
MyThread2 t = new MyThread2();
t.join(); // 当前线程进入阻塞,t线程执行,直到t线程结束。当前线程才可以继续。
}
}
class MyThread2 extends Thread{
}
2、关于多线程并发环境下,数据的安全问题。
2.1、为什么这个是重点?
以后在开发中,我们的项目都是运行在服务器当中,
而服务器已经将线程的定义,线程对象的创建,线程
的启动等,都已经实现完了。这些代码我们都不需要
编写。
最重要的是:你要知道,你编写的程序需要放到一个
多线程的环境下运行,你更需要关注的是这些数据
在多线程并发的环境下是否是安全的。(重点:*****)
2.2、什么时候数据在多线程并发的环境下会存在安全问题呢?
三个条件:
条件1:多线程并发。
条件2:有共享数据。
条件3:共享数据有修改的行为。
满足以上3个条件之后,就会存在线程安全问题。
2.3、怎么解决线程安全问题呢?
当多线程并发的环境下,有共享数据,并且这个数据还会被修改,此
时就存在
线程安全问题,怎么解决这个问题?
线程排队执行。(不能并发)。
用排队执行解决线程安全问题。
这种机制被称为:线程同步机制。
专业术语叫做:线程同步,实际上就是线程不能并发了,线程
必须排队执行。
怎么解决线程安全问题呀?
使用“线程同步机制”。
线程同步就是线程排队了,线程排队了就会牺牲一部分效率,没办法,数据安全
第一位,只有数据安全了,我们才可以谈效率。数据不安全,没有效率的事儿。
2.4、说到线程同步这块,涉及到这两个专业术语:
异步编程模型:
线程t1和线程t2,各自执行各自的,t1不管t2,t2不管t1,
谁也不需要等谁,这种编程模型叫做:异步编程模型。
其实就是:多线程并发(效率较高。)
异步就是并发。
同步编程模型:
线程t1和线程t2,在线程t1执行的时候,必须等待t2线程执行
结束,或者说在t2线程执行的时候,必须等待t1线程执行结束,
两个线程之间发生了等待关系,这就是同步编程模型。
效率较低。线程排队执行。
同步就是排队。
3、Java中有三大变量?【重要的内容。】
实例变量:在堆中。
静态变量:在方法区。
局部变量:在栈中。
以上三大变量中:
局部变量永远都不会存在线程安全问题。
因为局部变量不共享。(一个线程一个栈。)
局部变量在栈中。所以局部变量永远都不会共享。
实例变量在堆中,堆只有1个。
静态变量在方法区中,方法区只有1个。
堆和方法区都是多线程共享的,所以可能存在线程安全问题。
局部变量+常量:不会有线程安全问题。
成员变量:可能会有线程安全问题。
4、如果使用局部变量的话:
建议使用:StringBuilder。
因为局部变量不存在线程安全问题。选择StringBuilder。
StringBuffer效率比较低。
ArrayList是非线程安全的。
Vector是线程安全的。
HashMap HashSet是非线程安全的。
Hashtable是线程安全的。
5、总结:
synchronized有三种写法:
第一种:同步代码块
灵活
synchronized(线程共享对象){
同步代码块;
}
第二种:在实例方法上使用synchronized
表示共享对象一定是this
并且同步代码块是整个方法体。
第三种:在静态方法上使用synchronized
表示找类锁。
类锁永远只有1把。
就算创建了100个对象,那类锁也只有一把。
对象锁:1个对象1把锁,100个对象100把锁。
类锁:100个对象,也可能只是1把类锁。
6、聊一聊,我们以后开发中应该怎么解决线程安全问题?
是一上来就选择线程同步吗?synchronized
不是,synchronized会让程序的执行效率降低,用户体验不好。
系统的用户吞吐量降低。用户体验差。在不得已的情况下再选择
线程同步机制。
第一种方案:尽量使用局部变量代替“实例变量和静态变量”。
第二种方案:如果必须是实例变量,那么可以考虑创建多个对象,这样
实例变量的内存就不共享了。(一个线程对应1个对象,100个线程对应100个对象,
对象不共享,就没有数据安全问题了。)
第三种方案:如果不能使用局部变量,对象也不能创建多个,这个时候
就只能选择synchronized了。线程同步机制。
7、线程这块还有那些内容呢?列举一下
7.1、守护线程
7.2、定时器
7.3、实现线程的第三种方式:FutureTask方式,实现Callable接口。(JDK8新特性。)
7.4、关于Object类中的wait和notify方法。(生产者和消费者模式!)
1、线程这块还有那些内容呢?列举一下
1.1、守护线程
java语言中线程分为两大类:
一类是:用户线程
一类是:守护线程(后台线程)
其中具有代表性的就是:垃圾回收线程(守护线程)。
守护线程的特点:
一般守护线程是一个死循环,所有的用户线程只要结束,
守护线程自动结束。
注意:主线程main方法是一个用户线程。
守护线程用在什么地方呢?
每天00:00的时候系统数据自动备份。
这个需要使用到定时器,并且我们可以将定时器设置为守护线程。
一直在那里看着,每到00:00的时候就备份一次。所有的用户线程
如果结束了,守护线程自动退出,没有必要进行数据备份了。
1.2、定时器
定时器的作用:
间隔特定的时间,执行特定的程序。
每周要进行银行账户的总账操作。
每天要进行数据的备份操作。
在实际的开发中,每隔多久执行一段特定的程序,这种需求是很常见的,
那么在java中其实可以采用多种方式实现:
可以使用sleep方法,睡眠,设置睡眠时间,每到这个时间点醒来,执行
任务。这种方式是最原始的定时器。(比较low)
在java的类库中已经写好了一个定时器:java.util.Timer,可以直接拿来用。
不过,这种方式在目前的开发中也很少用,因为现在有很多高级框架都是支持
定时任务的。
在实际的开发中,目前使用较多的是Spring框架中提供的SpringTask框架,
这个框架只要进行简单的配置,就可以完成定时器的任务。
1.3、实现线程的第三种方式:实现Callable接口。(JDK8新特性。)
这种方式实现的线程可以获取线程的返回值。
之前讲解的那两种方式是无法获取线程返回值的,因为run方法返回void。
思考:
系统委派一个线程去执行一个任务,该线程执行完任务之后,可能
会有一个执行结果,我们怎么能拿到这个执行结果呢?
使用第三种方式:实现Callable接口方式。
1.4、关于Object类中的wait和notify方法。(生产者和消费者模式!)
第一:wait和notify方法不是线程对象的方法,是java中任何一个java对象
都有的方法,因为这两个方式是Object类中自带的。
wait方法和notify方法不是通过线程对象调用,
不是这样的:t.wait(),也不是这样的:t.notify()..不对。
第二:wait()方法作用?
Object o = new Object();
o.wait();
表示:
让正在o对象上活动的线程进入等待状态,无期限等待,
直到被唤醒为止。
o.wait();方法的调用,会让“当前线程(正在o对象上
活动的线程)”进入等待状态。
第三:notify()方法作用?
Object o = new Object();
o.notify();
表示:
唤醒正在o对象上等待的线程。
还有一个notifyAll()方法:
这个方法是唤醒o对象上处于等待的所有线程。
4.1.1 实现线程的第一种方式
package com. yxj. java. thread ;
public class ThreadTest02 {
public static void main ( String [ ] args) {
MyThread t = new MyThread ( ) ;
t. start ( ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
System . out. println ( "主线程--->" + i) ;
}
}
}
class MyThread extends Thread {
@Override
public void run ( ) {
for ( int i = 0 ; i < 1000 ; i++ ) {
System . out. println ( "分支线程--->" + i) ;
}
}
}
4.1.2 实现线程的第二种方式
package com. yxj. java. thread ;
public class ThreadTest03 {
public static void main ( String [ ] args) {
Thread t = new Thread ( new MyRunnable ( ) ) ;
t. start ( ) ;
for ( int i = 0 ; i < 100 ; i++ ) {
System . out. println ( "主线程--->" + i) ;
}
}
}
class MyRunnable implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
System . out. println ( "分支线程--->" + i) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. thread ;
public class ThreadTest04 {
public static void main ( String [ ] args) {
Thread t = new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
System . out. println ( "t线程---> " + i) ;
}
}
} ) ;
t. start ( ) ;
for ( int i = 0 ; i < 100 ; i++ ) {
System . out. println ( "main线程---> " + i) ;
}
}
}
package com. yxj. java. thread ;
public class ThreadTest05 {
public void doSome ( ) {
String name = Thread . currentThread ( ) . getName ( ) ;
System . out. println ( "------->" + name) ;
}
public static void main ( String [ ] args) {
ThreadTest05 tt = new ThreadTest05 ( ) ;
tt. doSome ( ) ;
Thread currentThread = Thread . currentThread ( ) ;
System . out. println ( currentThread. getName ( ) ) ;
MyThread2 t = new MyThread2 ( ) ;
t. setName ( "t1" ) ;
String tName = t. getName ( ) ;
System . out. println ( tName) ;
MyThread2 t2 = new MyThread2 ( ) ;
t2. setName ( "t2" ) ;
System . out. println ( t2. getName ( ) ) ;
t2. start ( ) ;
t. start ( ) ;
}
}
class MyThread2 extends Thread {
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
Thread currentThread = Thread . currentThread ( ) ;
System . out. println ( currentThread. getName ( ) + "-->" + i) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. thread ;
public class ThreadTest06 {
public static void main ( String [ ] args) {
for ( int i = 0 ; i < 10 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. thread ;
public class ThreadTest07 {
public static void main ( String [ ] args) {
Thread t = new MyThread3 ( ) ;
t. setName ( "t" ) ;
t. start ( ) ;
try {
t. sleep ( 1000 * 5 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "hello World!" ) ;
}
}
class MyThread3 extends Thread {
public void run ( ) {
for ( int i = 0 ; i < 10000 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. thread ;
public class ThreadTest08 {
public static void main ( String [ ] args) {
Thread t = new Thread ( new MyRunnable2 ( ) ) ;
t. setName ( "t" ) ;
t. start ( ) ;
try {
Thread . sleep ( 1000 * 5 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
t. interrupt ( ) ;
}
}
class MyRunnable2 implements Runnable {
@Override
public void run ( ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "---> begin" ) ;
try {
Thread . sleep ( 1000 * 60 * 60 * 24 * 365 ) ;
} catch ( InterruptedException e) {
}
System . out. println ( Thread . currentThread ( ) . getName ( ) + "---> end" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. thread ;
public class ThreadTest09 {
public static void main ( String [ ] args) {
Thread t = new Thread ( new MyRunnable3 ( ) ) ;
t. setName ( "t" ) ;
t. start ( ) ;
try {
Thread . sleep ( 1000 * 5 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
t. stop ( ) ;
}
}
class MyRunnable3 implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 10 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. thread ;
public class ThreadTest10 {
public static void main ( String [ ] args) {
MyRunable4 r = new MyRunable4 ( ) ;
Thread t = new Thread ( r) ;
t. setName ( "t" ) ;
t. start ( ) ;
try {
Thread . sleep ( 5000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
r. run = false ;
}
}
class MyRunable4 implements Runnable {
boolean run = true ;
@Override
public void run ( ) {
for ( int i = 0 ; i < 10 ; i++ ) {
if ( run) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
} else {
return ;
}
}
}
}
4.1.3 线程的优先级
package com. yxj. java. thread ;
public class ThreadTest11 {
public static void main ( String [ ] args) {
Thread . currentThread ( ) . setPriority ( 1 ) ;
Thread currentThread = Thread . currentThread ( ) ;
Thread t = new Thread ( new MyRunnable5 ( ) ) ;
t. setPriority ( 10 ) ;
t. setName ( "t" ) ;
t. start ( ) ;
for ( int i = 0 ; i < 10000 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "-->" + i) ;
}
}
}
class MyRunnable5 implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 10000 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "-->" + i) ;
}
}
}
Thread . yield ( )
package com. yxj. java. thread ;
public class ThreadTest12 {
public static void main ( String [ ] args) {
Thread t = new Thread ( new MyRunnable6 ( ) ) ;
t. setName ( "t" ) ;
t. start ( ) ;
for ( int i = 1 ; i <= 10000 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
}
}
}
class MyRunnable6 implements Runnable {
@Override
public void run ( ) {
for ( int i = 1 ; i <= 10000 ; i++ ) {
if ( i % 100 == 0 ) {
Thread . yield ( ) ;
}
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
}
}
}
join()
package com. yxj. java. thread ;
public class ThreadTest13 {
public static void main ( String [ ] args) {
System . out. println ( "main begin" ) ;
Thread t = new Thread ( new MyRunnable7 ( ) ) ;
t. setName ( "t" ) ;
t. start ( ) ;
try {
t. join ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "main over" ) ;
}
}
class MyRunnable7 implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 10000 ; i++ ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + i) ;
}
}
}
4.1.4 测试多线程下引发的问题
package com. yxj. java. threadsafe ;
public class Account {
private String actno;
private double balance;
public Account ( ) {
}
public Account ( String actno, double balance) {
this . actno = actno;
this . balance = balance;
}
public String getActno ( ) {
return actno;
}
public void setActno ( String actno) {
this . actno = actno;
}
public double getBalance ( ) {
return balance;
}
public void setBalance ( double balance) {
this . balance = balance;
}
public void withdraw ( double money) {
double before = this . getBalance ( ) ;
double after = before - money;
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
this . setBalance ( after) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. threadsafe ;
public class AccountThread extends Thread {
private Account act;
public AccountThread ( Account act) {
this . act = act;
}
public void run ( ) {
double money = 5000 ;
act. withdraw ( money) ;
System . out. println ( Thread . currentThread ( ) . getName ( ) + "对" + act. getActno ( ) + "取款" + money+ "成功,余额" + act. getBalance ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. threadsafe ;
public class Test {
public static void main ( String [ ] args) {
Account act = new Account ( "act-001" , 10000 ) ;
Thread t1 = new AccountThread ( act) ;
Thread t2 = new AccountThread ( act) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
t2. start ( ) ;
}
}
4.1.5 解决线程安全问题
package com. yxj. java. threadsafe2 ;
public class Account {
private String actno;
private double balance;
Object obj = new Object ( ) ;
public Account ( ) {
}
public Account ( String actno, double balance) {
this . actno = actno;
this . balance = balance;
}
public String getActno ( ) {
return actno;
}
public void setActno ( String actno) {
this . actno = actno;
}
public double getBalance ( ) {
return balance;
}
public void setBalance ( double balance) {
this . balance = balance;
}
public void withdraw ( double money) {
double before = this . getBalance ( ) ;
double after = before - money;
try {
Thread . sleep ( 1000 )
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
this . setBalance ( after) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. threadsafe2 ;
public class AccountThread extends Thread {
private Account act;
public AccountThread ( Account act) {
this . act = act;
}
public void run ( ) {
double money = 5000 ;
synchronized ( act) {
act. withdraw ( money) ;
}
System . out. println ( Thread . currentThread ( ) . getName ( ) + "对" + act. getActno ( ) + "取款" + money+ "成功,余额" + act. getBalance ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. threadsafe2 ;
public class Test {
public static void main ( String [ ] args) {
Account act = new Account ( "act-001" , 10000 ) ;
Thread t1 = new AccountThread ( act) ;
Thread t2 = new AccountThread ( act) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
t2. start ( ) ;
}
}
package com. yxj. java. threadsafe3 ;
public class Account {
private String actno;
private double balance;
public Account ( ) {
}
public Account ( String actno, double balance) {
this . actno = actno;
this . balance = balance;
}
public String getActno ( ) {
return actno;
}
public void setActno ( String actno) {
this . actno = actno;
}
public double getBalance ( ) {
return balance;
}
public void setBalance ( double balance) {
this . balance = balance;
}
public synchronized void withdraw ( double money) {
double before = this . getBalance ( ) ;
double after = before - money;
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
this . setBalance ( after) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. threadsafe3 ;
public class AccountThread extends Thread {
private Account act;
public AccountThread ( Account act) {
this . act = act;
}
public void run ( ) {
double money = 5000 ;
act. withdraw ( money) ;
System . out. println ( Thread . currentThread ( ) . getName ( ) + "对" + act. getActno ( ) + "取款" + money+ "成功,余额" + act. getBalance ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. threadsafe3 ;
public class Test {
public static void main ( String [ ] args) {
Account act = new Account ( "act-001" , 10000 ) ;
Thread t1 = new AccountThread ( act) ;
Thread t2 = new AccountThread ( act) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
t2. start ( ) ;
}
}
面试题
package com. yxj. java. exam1 ;
public class Exam01 {
public static void main ( String [ ] args) throws InterruptedException {
MyClass mc = new MyClass ( ) ;
Thread t1 = new MyThread ( mc) ;
Thread t2 = new MyThread ( mc) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
Thread . sleep ( 1000 ) ;
t2. start ( ) ;
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread ( MyClass mc) {
this . mc = mc;
}
public void run ( ) {
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t1" ) ) {
mc. doSome ( ) ;
}
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t2" ) ) {
mc. doOther ( ) ;
}
}
}
class MyClass {
public synchronized void doSome ( ) {
System . out. println ( "doSome begin" ) ;
try {
Thread . sleep ( 1000 * 10 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "doSome over" ) ;
}
public void doOther ( ) {
System . out. println ( "doOther begin" ) ;
System . out. println ( "doOther over" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. exam2 ;
public class Exam01 {
public static void main ( String [ ] args) throws InterruptedException {
MyClass mc = new MyClass ( ) ;
Thread t1 = new MyThread ( mc) ;
Thread t2 = new MyThread ( mc) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
Thread . sleep ( 1000 ) ;
t2. start ( ) ;
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread ( MyClass mc) {
this . mc = mc;
}
public void run ( ) {
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t1" ) ) {
mc. doSome ( ) ;
}
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t2" ) ) {
mc. doOther ( ) ;
}
}
}
class MyClass {
public synchronized void doSome ( ) {
System . out. println ( "doSome begin" ) ;
try {
Thread . sleep ( 1000 * 10 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "doSome over" ) ;
}
public synchronized void doOther ( ) {
System . out. println ( "doOther begin" ) ;
System . out. println ( "doOther over" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. exam3 ;
public class Exam01 {
public static void main ( String [ ] args) throws InterruptedException {
MyClass mc1 = new MyClass ( ) ;
MyClass mc2 = new MyClass ( ) ;
Thread t1 = new MyThread ( mc1) ;
Thread t2 = new MyThread ( mc2) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
Thread . sleep ( 1000 ) ;
t2. start ( ) ;
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread ( MyClass mc) {
this . mc = mc;
}
public void run ( ) {
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t1" ) ) {
mc. doSome ( ) ;
}
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t2" ) ) {
mc. doOther ( ) ;
}
}
}
class MyClass {
public synchronized void doSome ( ) {
System . out. println ( "doSome begin" ) ;
try {
Thread . sleep ( 1000 * 10 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "doSome over" ) ;
}
public synchronized void doOther ( ) {
System . out. println ( "doOther begin" ) ;
System . out. println ( "doOther over" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. exam4 ;
public class Exam01 {
public static void main ( String [ ] args) throws InterruptedException {
MyClass mc1 = new MyClass ( ) ;
MyClass mc2 = new MyClass ( ) ;
Thread t1 = new MyThread ( mc1) ;
Thread t2 = new MyThread ( mc2) ;
t1. setName ( "t1" ) ;
t2. setName ( "t2" ) ;
t1. start ( ) ;
Thread . sleep ( 1000 ) ;
t2. start ( ) ;
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread ( MyClass mc) {
this . mc = mc;
}
public void run ( ) {
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t1" ) ) {
mc. doSome ( ) ;
}
if ( Thread . currentThread ( ) . getName ( ) . equals ( "t2" ) ) {
mc. doOther ( ) ;
}
}
}
class MyClass {
public synchronized static void doSome ( ) {
System . out. println ( "doSome begin" ) ;
try {
Thread . sleep ( 1000 * 10 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "doSome over" ) ;
}
public synchronized static void doOther ( ) {
System . out. println ( "doOther begin" ) ;
System . out. println ( "doOther over" ) ;
}
}
4.1.6 死锁
package com. yxj. java. deadlock ;
public class DeadLock {
public static void main ( String [ ] args) {
Object o1 = new Object ( ) ;
Object o2 = new Object ( ) ;
Thread t1 = new MyThread1 ( o1, o2) ;
Thread t2 = new MyThread2 ( o1, o2) ;
t1. start ( ) ;
t2. start ( ) ;
}
}
class MyThread1 extends Thread {
Object o1;
Object o2;
public MyThread1 ( Object o1, Object o2) {
this . o1 = o1;
this . o2 = o2;
}
public void run ( ) {
synchronized ( o1) {
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
synchronized ( o2) {
}
}
}
}
class MyThread2 extends Thread {
Object o1;
Object o2;
public MyThread2 ( Object o1, Object o2) {
this . o1 = o1;
this . o2 = o2;
}
public void run ( ) {
synchronized ( o2) {
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
synchronized ( o1) {
}
}
}
}
Timer
package com. yxj. java. thread ;
import java. text. SimpleDateFormat ;
import java. util. Date ;
import java. util. Timer ;
import java. util. TimerTask ;
public class TimerTest {
public static void main ( String [ ] args) throws Exception {
Timer timer = new Timer ( ) ;
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ;
Date firstTime = sdf. parse ( "2020-03-14 09:34:30" ) ;
timer. schedule ( new TimerTask ( ) {
@Override
public void run ( ) {
}
} , firstTime, 1000 * 10 ) ;
}
}
class LogTimerTask extends TimerTask {
@Override
public void run ( ) {
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ;
String strTime = sdf. format ( new Date ( ) ) ;
System . out. println ( strTime + ":成功完成了一次数据备份!" ) ;
}
}
4.1.7 实现线程的第三种方式
package com. yxj. java. thread ;
import java. util. concurrent. Callable ;
import java. util. concurrent. FutureTask ;
public class ThreadTest15 {
public static void main ( String [ ] args) throws Exception {
FutureTask task = new FutureTask ( new Callable ( ) {
@Override
public Object call ( ) throws Exception {
System . out. println ( "call method begin" ) ;
Thread . sleep ( 1000 * 10 ) ;
System . out. println ( "call method end!" ) ;
int a = 100 ;
int b = 200 ;
return a + b;
}
} ) ;
Thread t = new Thread ( task) ;
t. start ( ) ;
Object obj = task. get ( ) ;
System . out. println ( "线程执行结果:" + obj) ;
System . out. println ( "hello world!" ) ;
}
}
4.1.8 使用wait方法和notify方法实现“生产者和消费者模式
package com. yxj. java. thread ;
import java. util. ArrayList ;
import java. util. List ;
public class ThreadTest16 {
public static void main ( String [ ] args) {
List list = new ArrayList ( ) ;
Thread t1 = new Thread ( new Producer ( list) ) ;
Thread t2 = new Thread ( new Consumer ( list) ) ;
t1. setName ( "生产者线程" ) ;
t2. setName ( "消费者线程" ) ;
t1. start ( ) ;
t2. start ( ) ;
}
}
class Producer implements Runnable {
private List list;
public Producer ( List list) {
this . list = list;
}
@Override
public void run ( ) {
while ( true ) {
synchronized ( list) {
if ( list. size ( ) > 0 ) {
try {
list. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
Object obj = new Object ( ) ;
list. add ( obj) ;
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + obj) ;
list. notifyAll ( ) ;
}
}
}
}
class Consumer implements Runnable {
private List list;
public Consumer ( List list) {
this . list = list;
}
@Override
public void run ( ) {
while ( true ) {
synchronized ( list) {
if ( list. size ( ) == 0 ) {
try {
list. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
Object obj = list. remove ( 0 ) ;
System . out. println ( Thread . currentThread ( ) . getName ( ) + "--->" + obj) ;
list. notifyAll ( ) ;
}
}
}
}
5.1 反射
反射机制相关的重要的类有哪些?
java.lang.Class:代表整个字节码,代表一个类型,代表整个类。
java.lang.reflect.Method:代表字节码中的方法字节码。代表类中的方法。
java.lang.reflect.Constructor:代表字节码中的构造方法字节码。代表类中的构造方法
java.lang.reflect.Field:代表字节码中的属性字节码。代表类中的成员变量(静态变量+实例变量)
1、反射机制
1.1、什么是反射机制?反射机制有什么用?
反射机制:可以操作字节码文件
作用:可以让程序更加灵活。
1.2、反射机制相关的类在哪个包下?
java.lang.reflect.*;
1.3、反射机制相关的主要的类?
java.lang.Class
java.lang.reflect.Method;
java.lang.reflect.Constructor;
java.lang.reflect.Field;
1.4、在java中获取Class的三种方式?
第一种:
Class c = Class.forName("完整类名");
第二种:
Class c = 对象.getClass();
第三种:
Class c = int.class;
Class c = String.class;
1.5、获取了Class之后,可以调用无参数构造方法来实例化对象
//c代表的就是日期Date类型
Class c = Class.forName("java.util.Date");
//实例化一个Date日期类型的对象
Object obj = c.newInstance();
一定要注意:
newInstance()底层调用的是该类型的无参数构造方法。
如果没有这个无参数构造方法会出现"实例化"异常。
1.6、如果你只想让一个类的“静态代码块”执行的话,你可以怎么做?
Class.forName("该类的类名");
这样类就加载,类加载的时候,静态代码块执行!!!!
在这里,对该方法的返回值不感兴趣,主要是为了使用“类加载”这个动作。
1.7、关于路径问题?
String path = Thread.currentThread().getContextClassLoader()
.getResource("写相对路径,但是这个相对路径从src出发开始找").getPath();
String path = Thread.currentThread().getContextClassLoader()
.getResource("abc").getPath(); //必须保证src下有abc文件。
String path = Thread.currentThread().getContextClassLoader()
.getResource("a/db").getPath(); //必须保证src下有a目录,a目录下有db文件。
String path = Thread.currentThread().getContextClassLoader()
.getResource("com/yxj/test.properties").getPath();
//必须保证src下有com目录,com目录下有yxj目录。
//yxj目录下有test.properties文件。
这种方式是为了获取一个文件的绝对路径。(通用方式,不会受到环境移植的影响。)
但是该文件要求放在类路径下,换句话说:也就是放到src下面。
src下是类的根路径。
直接以流的形式返回:
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("com/yxj/test.properties");
1.8、IO + Properties,怎么快速绑定属性资源文件?
//要求:第一这个文件必须在类路径下
//第二这个文件必须是以.properties结尾。
ResourceBundle bundle = ResourceBundle.getBundle("com/yxj/test");
String value = bundle.getString(key);
2、今日反射机制的重点内容
2.1、通过反射机制访问对象的某个属性。
2.2、通过反射机制调用对象的某个方法。
2.3、通过反射机制调用某个构造方法实例化对象。
2.4、通过反射机制获取父类以及父类型接口。
package com. yxj. java. reflect ;
import java. util. Date ;
public class ReflectTest01 {
public static void main ( String [ ] args) {
Class c1 = null ;
Class c2 = null ;
try {
c1 = Class . forName ( "java.lang.String" ) ;
c2 = Class . forName ( "java.util.Date" ) ;
Class c3 = Class . forName ( "java.lang.Integer" ) ;
Class c4 = Class . forName ( "java.lang.System" ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
String s = "abc" ;
Class x = s. getClass ( ) ;
System . out. println ( c1 == x) ;
Date time = new Date ( ) ;
Class y = time. getClass ( ) ;
System . out. println ( c2 == y) ;
Class z = String . class ;
Class k = Date . class ;
Class f = int . class ;
Class e = double . class ;
System . out. println ( x == z) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. reflect ;
import com. yxj. java. bean. User ;
public class ReflectTest02 {
public static void main ( String [ ] args) {
User user = new User ( ) ;
System . out. println ( user) ;
try {
Class c = Class . forName ( "com.yxj.java.bean.User" ) ;
Object obj = c. newInstance ( ) ;
System . out. println ( obj) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IllegalAccessException e) {
e. printStackTrace ( ) ;
} catch ( InstantiationException e) {
e. printStackTrace ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package com. yxj. java. reflect ;
import com. yxj. java. bean. User ;
import java. io. FileReader ;
import java. util. Properties ;
public class ReflectTest03 {
public static void main ( String [ ] args) throws Exception {
FileReader reader = new FileReader ( "chapter25/classinfo2.properties" ) ;
Properties pro = new Properties ( ) ;
pro. load ( reader) ;
reader. close ( ) ;
String className = pro. getProperty ( "className" ) ;
Class c = Class . forName ( className) ;
Object obj = c. newInstance ( ) ;
System . out. println ( obj) ;
}
}
package com. yxj. java. reflect ;
public class ReflectTest04 {
public static void main ( String [ ] args) {
try {
Class . forName ( "com.yxj.java.reflect.MyClass" ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
public class ReflectTest04 {
public static void main ( String [ ] args) {
try {
Class . forName ( "com.yxj.java.reflect.MyClass" ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
}
}
package com. yxj. java. reflect ;
public class MyClass {
static {
System . out. println ( "MyClass类的静态代码块执行了!" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import java. lang. reflect. Field ;
import java. lang. reflect. Modifier ;
public class ReflectTest05 {
public static void main ( String [ ] args) throws Exception {
Class studentClass = Class . forName ( "com.yxj.java.bean.Student" ) ;
String className = studentClass. getName ( ) ;
System . out. println ( "完整类名:" + className) ;
String simpleName = studentClass. getSimpleName ( ) ;
System . out. println ( "简类名:" + simpleName) ;
Field [ ] fields = studentClass. getFields ( ) ;
System . out. println ( fields. length) ;
Field f = fields[ 0 ] ;
String fieldName = f. getName ( ) ;
System . out. println ( fieldName) ;
Field [ ] fs = studentClass. getDeclaredFields ( ) ;
System . out. println ( fs. length) ;
System . out. println ( "==================================" ) ;
for ( Field field : fs) {
int i = field. getModifiers ( ) ;
System . out. println ( i) ;
String modifierString = Modifier . toString ( i) ;
System . out. println ( modifierString) ;
Class fieldType = field. getType ( ) ;
String fName = fieldType. getSimpleName ( ) ;
System . out. println ( fName) ;
System . out. println ( field. getName ( ) ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. bean ;
public class Student {
private String name;
protected int age;
boolean sex;
public int no;
public static final double MATH_PI = 3.1415926 ;
}
package com. yxj. java. reflect ;
import java. lang. reflect. Field ;
import java. lang. reflect. Modifier ;
public class ReflectTest06 {
public static void main ( String [ ] args) throws Exception {
StringBuilder s = new StringBuilder ( ) ;
Class studentClass = Class . forName ( "java.lang.Thread" ) ;
s. append ( Modifier . toString ( studentClass. getModifiers ( ) ) + " class " + studentClass. getSimpleName ( ) + " {\n" ) ;
Field [ ] fields = studentClass. getDeclaredFields ( ) ;
for ( Field field : fields) {
s. append ( "\t" ) ;
s. append ( Modifier . toString ( field. getModifiers ( ) ) ) ;
s. append ( " " ) ;
s. append ( field. getType ( ) . getSimpleName ( ) ) ;
s. append ( " " ) ;
s. append ( field. getName ( ) ) ;
s. append ( ";\n" ) ;
}
s. append ( "}" ) ;
System . out. println ( s) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import com. yxj. java. bean. Student ;
import java. lang. reflect. Field ;
public class ReflectTest07 {
public static void main ( String [ ] args) throws Exception {
Student s = new Student ( ) ;
s. no = 1111 ;
System . out. println ( s. no) ;
Class studentClass = Class . forName ( "com.yxj.java.bean.Student" ) ;
Object obj = studentClass. newInstance ( ) ;
Field noFiled = studentClass. getDeclaredField ( "no" ) ;
noFiled. set ( obj, 22222 ) ;
System . out. println ( noFiled. get ( obj) ) ;
Field nameField = studentClass. getDeclaredField ( "name" ) ;
nameField. setAccessible ( true ) ;
nameField. set ( obj, "jackson" ) ;
System . out. println ( nameField. get ( obj) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import java. lang. reflect. Method ;
import java. lang. reflect. Modifier ;
public class ReflectTest08 {
public static void main ( String [ ] args) throws Exception {
Class userServiceClass = Class . forName ( "com.yxj.java.service.UserService" ) ;
Method [ ] methods = userServiceClass. getDeclaredMethods ( ) ;
for ( Method method : methods) {
System . out. println ( Modifier . toString ( method. getModifiers ( ) ) ) ;
System . out. println ( method. getReturnType ( ) . getSimpleName ( ) ) ;
System . out. println ( method. getName ( ) ) ;
Class [ ] parameterTypes = method. getParameterTypes ( ) ;
for ( Class parameterType : parameterTypes) {
System . out. println ( parameterType. getSimpleName ( ) ) ;
}
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import java. lang. reflect. Method ;
import java. lang. reflect. Modifier ;
public class ReflectTest09 {
public static void main ( String [ ] args) throws Exception {
StringBuilder s = new StringBuilder ( ) ;
Class userServiceClass = Class . forName ( "java.lang.String" ) ;
s. append ( Modifier . toString ( userServiceClass. getModifiers ( ) ) + " class " + userServiceClass. getSimpleName ( ) + " {\n" ) ;
Method [ ] methods = userServiceClass. getDeclaredMethods ( ) ;
for ( Method method : methods) {
s. append ( "\t" ) ;
s. append ( Modifier . toString ( method. getModifiers ( ) ) ) ;
s. append ( " " ) ;
s. append ( method. getReturnType ( ) . getSimpleName ( ) ) ;
s. append ( " " ) ;
s. append ( method. getName ( ) ) ;
s. append ( "(" ) ;
Class [ ] parameterTypes = method. getParameterTypes ( ) ;
for ( Class parameterType : parameterTypes) {
s. append ( parameterType. getSimpleName ( ) ) ;
s. append ( "," ) ;
}
s. deleteCharAt ( s. length ( ) - 1 ) ;
s. append ( "){}\n" ) ;
}
s. append ( "}" ) ;
System . out. println ( s) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import com. yxj. java. service. UserService ;
import java. lang. reflect. Method ;
public class ReflectTest10 {
public static void main ( String [ ] args) throws Exception {
UserService userService = new UserService ( ) ;
boolean loginSuccess = userService. login ( "admin" , "123" ) ;
System . out. println ( loginSuccess ? "登录成功" : "登录失败" ) ;
Class userServiceClass = Class . forName ( "com.yxj.java.service.UserService" ) ;
Object obj = userServiceClass. newInstance ( ) ;
Method loginMethod = userServiceClass. getDeclaredMethod ( "login" , String . class , String . class ) ;
Object retValue = loginMethod. invoke ( obj, "admin" , "123123" ) ;
System . out. println ( retValue) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. bean ;
public class Vip {
int no;
String name;
String birth;
boolean sex;
public Vip ( ) {
}
public Vip ( int no) {
this . no = no;
}
public Vip ( int no, String name) {
this . no = no;
this . name = name;
}
public Vip ( int no, String name, String birth) {
this . no = no;
this . name = name;
this . birth = birth;
}
public Vip ( int no, String name, String birth, boolean sex) {
this . no = no;
this . name = name;
this . birth = birth;
this . sex = sex;
}
@Override
public String toString ( ) {
return "Vip{" +
"no=" + no +
", name='" + name + '\'' +
", birth='" + birth + '\'' +
", sex=" + sex +
'}' ;
}
}
package com. yxj. java. reflect ;
import java. lang. reflect. Constructor ;
import java. lang. reflect. Modifier ;
public class ReflectTest11 {
public static void main ( String [ ] args) throws Exception {
StringBuilder s = new StringBuilder ( ) ;
Class vipClass = Class . forName ( "java.lang.String" ) ;
s. append ( Modifier . toString ( vipClass. getModifiers ( ) ) ) ;
s. append ( " class " ) ;
s. append ( vipClass. getSimpleName ( ) ) ;
s. append ( "{\n" ) ;
Constructor [ ] constructors = vipClass. getDeclaredConstructors ( ) ;
for ( Constructor constructor : constructors) {
s. append ( "\t" ) ;
s. append ( Modifier . toString ( constructor. getModifiers ( ) ) ) ;
s. append ( " " ) ;
s. append ( vipClass. getSimpleName ( ) ) ;
s. append ( "(" ) ;
Class [ ] parameterTypes = constructor. getParameterTypes ( ) ;
for ( Class parameterType : parameterTypes) {
s. append ( parameterType. getSimpleName ( ) ) ;
s. append ( "," ) ;
}
if ( parameterTypes. length > 0 ) {
s. deleteCharAt ( s. length ( ) - 1 ) ;
}
s. append ( "){}\n" ) ;
}
s. append ( "}" ) ;
System . out. println ( s) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import com. yxj. java. bean. Vip ;
import java. lang. reflect. Constructor ;
public class ReflectTest12 {
public static void main ( String [ ] args) throws Exception {
Vip v1 = new Vip ( ) ;
Vip v2 = new Vip ( 110 , "zhangsan" , "2001-10-11" , true ) ;
Class c = Class . forName ( "com.yxj.java.bean.Vip" ) ;
Object obj = c. newInstance ( ) ;
System . out. println ( obj) ;
Constructor con = c. getDeclaredConstructor ( int . class , String . class , String . class , boolean . class ) ;
Object newObj = con. newInstance ( 110 , "jackson" , "1990-10-11" , true ) ;
System . out. println ( newObj) ;
Constructor con2 = c. getDeclaredConstructor ( ) ;
Object newObj2 = con2. newInstance ( ) ;
System . out. println ( newObj2) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
public class ReflectTest13 {
public static void main ( String [ ] args) throws Exception {
Class stringClass = Class . forName ( "java.lang.String" ) ;
Class superClass = stringClass. getSuperclass ( ) ;
System . out. println ( superClass. getName ( ) ) ;
Class [ ] interfaces = stringClass. getInterfaces ( ) ;
for ( Class in : interfaces) {
System . out. println ( in. getName ( ) ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
6.1 路径问题
package com. yxj. java. reflect ;
import java. io. FileReader ;
public class AboutPath {
public static void main ( String [ ] args) throws Exception {
String path = Thread . currentThread ( ) . getContextClassLoader ( )
. getResource ( "classinfo2.properties" ) . getPath ( ) ;
System . out. println ( path) ;
String path2 = Thread . currentThread ( ) . getContextClassLoader ( )
. getResource ( "com/yxj/java/bean/db.properties" ) . getPath ( ) ;
System . out. println ( path2) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import java. io. FileReader ;
import java. io. InputStream ;
import java. util. Properties ;
public class IoPropertiesTest {
public static void main ( String [ ] args) throws Exception {
InputStream reader = Thread . currentThread ( ) . getContextClassLoader ( )
. getResourceAsStream ( "classinfo2.properties" ) ;
Properties pro = new Properties ( ) ;
pro. load ( reader) ;
reader. close ( ) ;
String className = pro. getProperty ( "className" ) ;
System . out. println ( className) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. reflect ;
import java. util. ResourceBundle ;
public class ResourceBundleTest {
public static void main ( String [ ] args) {
ResourceBundle bundle = ResourceBundle . getBundle ( "com/yxj/java/bean/db" ) ;
String className = bundle. getString ( "className" ) ;
System . out. println ( className) ;
}
}
7.1 注解
注解Annotation是一种引用数据类型。编译之后也是生
成xxx. class文件。
怎么自定义注解呢?语法格式?
[ 修饰符列表] @interface 注解类型名{
}
注解怎么使用,用在什么地方?
第一:注解使用时的语法格式是:
@注解类型名
第二:注解可以出现在类上、属性上、方法上、变量上等... .
注解还可以出现在注解类型上。
JDK 内置了哪些注解呢?
java. lang包下的注释类型:
掌握:
Deprecated 用 @Deprecated 注释的程序元素,
不鼓励程序员使用这样的元素,通常是因为它很危险或存在更好的选择。
掌握:
Override 表示一个方法声明打算重写超类中的另一个方法声明。
不用掌握:
SuppressWarnings 指示应该在注释元素(以及包含在该注释元素中的
所有程序元素)中取消显示指定的编译器警告。
元注解
什么是元注解?
用来标注“注解类型”的“注解”,称为元注解。
常见的元注解有哪些?
Target
Retention
关于Target注解:
这是一个元注解,用来标注“注解类型”的“注解”
这个Target注解用来标注“被标注的注解”可以出现在哪些位置上。
@Target ( ElementType. METHOD ) :表示“被标注的注解”只能出现在方法上。
@Target ( value= { CONSTRUCTOR , FIELD , LOCAL_VARIABLE , METHOD , PACKAGE , MODULE , PARAMETER , TYPE } )
表示该注解可以出现在:
构造方法上
字段上
局部变量上
方法上
... .
类上...
关于Retention注解:
这是一个元注解,用来标注“注解类型”的“注解”
这个Retention注解用来标注“被标注的注解”最终保存在哪里。
@Retention ( RetentionPolicy. SOURCE ) :表示该注解只被保留在java源文件中。注解只在源码阶段保留,在编译器完整编译之后,它将被丢弃忽视;比如@Override, @SuppressWarnings
@Retention ( RetentionPolicy. CLASS ) :表示该注解被保存在class 文件中。注解只被保留到编译进行的时候,它并不会被加载到 JVM 中;
@Retention ( RetentionPolicy. RUNTIME ) :表示该注解被保存在class 文件中,并且可以被反射机制所读取。 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们;
Retention的源代码
public @interface Retention {
RetentionPolicy value ( ) ;
}
RetentionPolicy的源代码:
public enum RetentionPolicy {
SOURCE ,
CLASS ,
RUNTIME
}
@Retention ( RetentionPolicy. RUNTIME )
public @interface MyAnnotation { }
Target的源代码
@Documented
@Retention ( RetentionPolicy. RUNTIME )
@Target ( ElementType. ANNOTATION_TYPE )
public @interface Target {
ElementType[ ] value ( ) ;
}
public enum ElementType {
TYPE ,
FIELD ,
METHOD ,
PARAMETER ,
CONSTRUCTOR ,
LOCAL_VARIABLE ,
ANNOTATION_TYPE ,
PACKAGE ,
TYPE_PARAMETER ,
TYPE_USE
}
ElementType. CONSTRUCTOR : 对构造方法进行注解;
ElementType. ANNOTATION_TYPE : 对注解进行注解;
ElementType. FIELD : 对属性、成员变量、成员对象(包括 enum 实例)进行注解;
ElementType. LOCAL_VARIABLE : 对局部变量进行注解;
ElementType. METHOD : 对方法进行注解;
ElementType. PACKAGE : 对包进行注解;
ElementType. PARAMETER : 对描述参数进行注解;
ElementType. TYPE : 对类、接口、枚举进行注解;
@Documented
@Documented 是一个简单的标记注解,表示是否将注解信
息添加在 Java 文档,即 Javadoc 中。
@Inherited
Inherited 是指继承,@Inherited 定义了一个注释
与子类的关系。如果一个超类带有 @Inherited 注
解,那么对于该超类,它的子类如果没有被任何注
解应用的话,那么这个子类就继承了超类的注解。
@Inherited
@Retention ( RetentionPolicy. RUNTIME )
@interface Test { }
@Test
public class A { }
public class B extends A { }
注解 Test 被 @Inherited 修饰,之后类 A 被 Test 注解,类 B 继承 A , 类 B 也拥有 Test 这个注解。
@Repeatable
@Repeatable 是 Java 8 中加入的,是指可重复的意思。通常使用 @Repeatable 的时候指注解的值可以同时取多个
@interface Persons {
Person[ ] value ( ) ;
}
@Repeatable ( Persons. class)
@interface Person {
String role default "" ;
}
@Person ( role= "artist" )
@Person ( role= "coder" )
@Person ( role= "PM" )
public class SuperMan {
...
}
上面的代码通过 @Repeatable 定义了 Person,而 @Repeatable 后面括号的类相当于一个容器注解。容器注解就是用来存放其它注解的地方,它本身也是一个注解。
@Documented
@Retention ( RetentionPolicy. RUNTIME )
@Target ( ElementType. ANNOTATION_TYPE )
public @interface Repeatable {
Class< ? extends Annotation > value ( ) ;
}
注解在开发中有什么用呢?
需求:
假设有这样一个注解,叫做:@Id
这个注解只能出现在类上面,当这个类上有这个注解的时候,
要求这个类中必须有一个int类型的id属性。如果没有这个属性
就报异常。如果有这个属性则正常执行!
package com. yxj. java. annotation ;
public @interface MyAnnotation {
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation ;
@MyAnnotation
public @interface OtherAnnotation {
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation ;
@MyAnnotation
public class AnnotationTest01 {
@MyAnnotation
private int no;
@MyAnnotation
public AnnotationTest01 ( ) { }
@MyAnnotation
public static void m1 ( ) {
@MyAnnotation
int i = 100 ;
}
@MyAnnotation
public void m2 ( @MyAnnotation
String name,
@MyAnnotation
int k) {
}
}
@MyAnnotation
interface MyInterface {
}
@MyAnnotation
enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation ;
public class AnnotationTest02 {
private int no;
@Override
public String toString ( ) {
return "toString" ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation ;
@Deprecated
public class AnnotationTest03 {
@Deprecated
private String s;
public static void main ( String [ ] args) {
AnnotationTest03 at = new AnnotationTest03 ( ) ;
at. doSome ( ) ;
}
@Deprecated
public void doSome ( ) {
System . out. println ( "do something!" ) ;
}
@Deprecated
public static void doOther ( ) {
System . out. println ( "do other..." ) ;
}
}
class T {
public static void main ( String [ ] args) {
AnnotationTest03 at = new AnnotationTest03 ( ) ;
at. doSome ( ) ;
AnnotationTest03 . doOther ( ) ;
try {
Class c = Class . forName ( "java.util.Date" ) ;
Object obj = c. newInstance ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation2 ;
public @interface MyAnnotation {
String name ( ) ;
String color ( ) ;
int age ( ) default 25 ;
}
package com. yxj. java. annotation2 ;
public class MyAnnotationTest {
@MyAnnotation ( name = "zhangsan" , color = "红色" )
public void doSome ( ) {
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation4 ;
public @interface MyAnnotation {
int value1 ( ) ;
String value2 ( ) ;
int [ ] value3 ( ) ;
String [ ] value4 ( ) ;
Season value5 ( ) ;
Season [ ] value6 ( ) ;
Class parameterType ( ) ;
Class [ ] parameterTypes ( ) ;
}
package com. yxj. java. annotation4 ;
public @interface OtherAnnotation {
int age ( ) ;
String [ ] email ( ) ;
Season [ ] seasonArray ( ) ;
}
package com. yxj. java. annotation4 ;
public enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}
package com. yxj. java. annotation4 ;
public class OtherAnnotationTest {
@OtherAnnotation ( age = 25 , email = { "zhangsan@123.com" , "zhangsan@sohu.com" } , seasonArray = Season . WINTER)
public void doSome ( ) {
}
@OtherAnnotation ( age = 25 , email = "zhangsan@123.com" , seasonArray = { Season . SPRING, Season . SUMMER} )
public void doOther ( ) {
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation5 ;
import java. lang. annotation. ElementType ;
import java. lang. annotation. Retention ;
import java. lang. annotation. RetentionPolicy ;
import java. lang. annotation. Target ;
@Target ( { ElementType . TYPE, ElementType . METHOD} )
@Retention ( RetentionPolicy . RUNTIME)
public @interface MyAnnotation {
String value ( ) default "北京大兴区" ;
}
package com. yxj. java. annotation5 ;
@MyAnnotation ( "上海浦东区" )
public class MyAnnotationTest {
int i;
public MyAnnotationTest ( ) {
}
@MyAnnotation
public void doSome ( ) {
int i;
}
}
package com. yxj. java. annotation5 ;
public class ReflectAnnotationTest {
public static void main ( String [ ] args) throws Exception {
Class c = Class . forName ( "com.yxj.java.annotation5.MyAnnotationTest" ) ;
if ( c. isAnnotationPresent ( MyAnnotation . class ) ) {
MyAnnotation myAnnotation = ( MyAnnotation ) c. getAnnotation ( MyAnnotation . class ) ;
String value = myAnnotation. value ( ) ;
System . out. println ( value) ;
}
Class stringClass = Class . forName ( "java.lang.String" ) ;
System . out. println ( stringClass. isAnnotationPresent ( MyAnnotation . class ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation6 ;
import java. lang. annotation. ElementType ;
import java. lang. annotation. Retention ;
import java. lang. annotation. RetentionPolicy ;
import java. lang. annotation. Target ;
@Retention ( RetentionPolicy . RUNTIME)
@Target ( ElementType . METHOD)
public @interface MyAnnotation {
String username ( ) ;
String password ( ) ;
}
package com. yxj. java. annotation6 ;
import java. lang. reflect. Method ;
public class MyAnnotationTest {
@MyAnnotation ( username = "admin" , password = "456456" )
public void doSome ( ) {
}
public static void main ( String [ ] args) throws Exception {
Class c = Class . forName ( "com.yxj.java.annotation6.MyAnnotationTest" ) ;
Method doSomeMethod = c. getDeclaredMethod ( "doSome" ) ;
if ( doSomeMethod. isAnnotationPresent ( MyAnnotation . class ) ) {
MyAnnotation myAnnotation = doSomeMethod. getAnnotation ( MyAnnotation . class ) ;
System . out. println ( myAnnotation. username ( ) ) ;
System . out. println ( myAnnotation. password ( ) ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
package com. yxj. java. annotation7 ;
@MustHasIdPropertyAnnotation
public class User {
int id;
String name;
String password;
}
package com. yxj. java. annotation7 ;
public class HasNotIdPropertyException extends RuntimeException {
public HasNotIdPropertyException ( ) {
}
public HasNotIdPropertyException ( String s) {
super ( s) ;
}
}
package com. yxj. java. annotation7 ;
import java. lang. reflect. Field ;
public class Test {
public static void main ( String [ ] args) throws Exception {
Class userClass = Class . forName ( "com.yxj.java.annotation7.User" ) ;
if ( userClass. isAnnotationPresent ( MustHasIdPropertyAnnotation . class ) ) {
Field [ ] fields = userClass. getDeclaredFields ( ) ;
boolean isOk = false ;
for ( Field field : fields) {
if ( "id" . equals ( field. getName ( ) ) && "int" . equals ( field. getType ( ) . getSimpleName ( ) ) ) {
isOk = true ;
break ;
}
}
if ( ! isOk) {
throw new HasNotIdPropertyException ( "被@MustHasIdPropertyAnnotation注解标注的类中必须要有一个int类型的id属性!" ) ;
}
}
}
}
7.1.1 自定义注解
自定义注解类编写的规则:
注解类型定义为 @interface,所有的注解会自动继承 java.lang.Annotation 这一接口,而且不能再去继承其他的类或接口;
参数成员只能用 public 或 default 两个关键字修饰;
参数成员只能用基本类型:byte, short, char, int, long, float, double, boolean,以及 String, Enum, Class, Annotations 等数据类型,以及这些类型的数组;
要获取类方法和字段的注解信息,必须通过 Java 的反射技术;
注解也可以不定义成员变量,但这样的注解没有什么卵用;
自定义注解需要使用元注解进行编写;
以水果与水果供应商为例:
水果名称注解 FruitName . java:
package com. yxj. FruitAnnotation ;
import java. lang. annotation. Documented ;
import java. lang. annotation. Retention ;
import java. lang. annotation. Target ;
import static java. lang. annotation. ElementType . FIELD;
import static java. lang. annotation. RetentionPolicy . RUNTIME;
@Target ( FIELD)
@Retention ( RUNTIME)
@Documented
public @interface FruitName {
String value ( ) default "" ;
}
@Target ( FIELD)
@Retention ( RUNTIME)
@Documented
public @interface FruitName {
String value ( ) default "" ;
}
水果颜色注解 FruitColor . java
package com. yxj. FruitAnnotation ;
import java. lang. annotation. Documented ;
import java. lang. annotation. Retention ;
import java. lang. annotation. Target ;
import static java. lang. annotation. ElementType . FIELD;
import static java. lang. annotation. RetentionPolicy . RUNTIME;
@Target ( FIELD)
@Retention ( RUNTIME)
@Documented
public @interface FruitColor {
public enum Color { BLUE, RED, GREEN} ;
Color fruitColor ( ) default Color . GREEN;
}
水果供应者注解 FruitProvider . java:
package com. yxj. FruitAnnotation ;
import java. lang. annotation. Documented ;
import java. lang. annotation. Retention ;
import java. lang. annotation. Target ;
import static java. lang. annotation. ElementType . FIELD;
import static java. lang. annotation. RetentionPolicy . RUNTIME;
@Target ( FIELD)
@Retention ( RUNTIME)
@Documented
public @interface FruitProvider {
public int id ( ) default - 1 ;
public String name ( ) default "" ;
public String address ( ) default "" ;
}
注解处理器 FruitInfoUtil . java:
package com. grq. FruitAnnotation ;
import java. lang. reflect. Field ;
public class FruitInfoUtil {
public static void getFruitInfo ( Class < ? > clazz) {
String strFruitName= " 水果名称:" ;
String strFruitColor= " 水果颜色:" ;
String strFruitProvicer= "供应商信息:" ;
Field [ ] fields = clazz. getDeclaredFields ( ) ;
for ( Field field : fields) {
if ( field. isAnnotationPresent ( FruitName . class ) ) {
FruitName fruitName = ( FruitName ) field. getAnnotation ( FruitName . class ) ;
strFruitName= strFruitName+ fruitName. value ( ) ;
System . out. println ( strFruitName) ;
}
else if ( field. isAnnotationPresent ( FruitColor . class ) ) {
FruitColor fruitColor= ( FruitColor ) field. getAnnotation ( FruitColor . class ) ;
strFruitColor= strFruitColor+ fruitColor. fruitColor ( ) . toString ( ) ;
System . out. println ( strFruitColor) ;
}
else if ( field. isAnnotationPresent ( FruitProvider . class ) ) {
FruitProvider fruitProvider= ( FruitProvider ) field. getAnnotation ( FruitProvider . class ) ;
strFruitProvicer= " 供应商编号:" + fruitProvider. id ( ) + " 供应商名称:" + fruitProvider. name ( ) + " 供应商地址:" + fruitProvider. address ( ) ;
System . out. println ( strFruitProvicer) ;
}
}
}
}
苹果 Apple . java:
package com. grq. FruitAnnotation ;
public class Apple {
@FruitName ( "Apple" )
private String appleName;
@FruitColor ( fruitColor = FruitColor. Color . RED)
private String appleColor;
@FruitProvider ( id= 1 , name= "从前慢有限集团" , address= "从前慢有限集团大厦" )
private String appleProvider;
public void setAppleColor ( String appleColor) {
this . appleColor = appleColor;
}
public String getAppleColor ( ) {
return appleColor;
}
public void setAppleName ( String appleName) {
this . appleName = appleName;
}
public String getAppleName ( ) {
return appleName;
}
public void setAppleProvider ( String appleProvider) {
this . appleProvider = appleProvider;
}
public String getAppleProvider ( ) {
return appleProvider;
}
public void displayName ( ) {
System . out. println ( "水果的名字是:苹果" ) ;
}
}
测试输出水果信息 FruitTestAnnotation :
package com. yxj. FruitAnnotation ;
public class TestFruitAnnotation {
public static void main ( String [ ] args) {
FruitInfoUtil . getFruitInfo ( Apple . class ) ;
}
}
运行后的测试结果为:
水果名称:Apple
水果颜色:RED
供应商编号:1 供应商名称:从前慢有限集团 供应商地址:从前慢有限集团大厦