JavaSE - Advance高级 07
1. 多线程
进程 - 独立
线程 - 顺序流结构
多线程 - 同时执行顺序流
cpu - 时间片段
1.1 线程创建、启动
extends Thread
implements Runnable
重写run ( )
cpu Thread thread = new Thread ( traget) ;
data target - > Runnable
code run ( ) 方法
start ( )
1.2 方法
setPriority ( int ) 1 ~ 10 MIN- RIORITY NORM- RIORITY MAX- RIORITY
setDaemon ( boolean )
调度
join ( )
sleep ( long ms)
yield ( )
stop停止
1.3 线程池 - 循环利用
ExecutorService threadPool = Executors. newFixedThreadPool ( int nThreads) ;
threadPool. submit ( Runnable) ;
threadPool. submit ( Runnable) ;
public void run ( )
threadPool. shutdown ( ) ; . shutdownNow ( ) ;
Future futrue = threadPool. submit ( Callable) ;
public T call ( )
futrue. get ( ) ;
FutureTask task = new FutrueTask ( Callable) ;
new Thread ( task) . start ( ) ;
task. get ( ) ;
1.4 Timer计时器
Timer timer = new Timer ( ) ;
timer. schedule ( TimerTask, Date)
timer. schedule ( TimerTask, Date, long period)
timer. schedule ( TimerTask, deley)
timer. schedule ( TimerTask, deley, long period)
1.5 线程安全
同一数据
if ( num > 0 ) {
num-- ;
sleep ( 100 ) ;
}
状态
新建、可运行、运行、死亡
阻塞
等待
同步: - 一次一个线程执行代码
1 :同步代码块
synchronized ( object) {
. . .
}
2 :同步方法
public synchronized void method ( . . ) {
. . .
}
3 :Lock全局锁
Lock lock = new ReentrantLock ( ) ;
方法 {
lock. lock ( ) ;
try {
. . .
} finally {
lock. unlock ( ) ;
}
}
1.6 线程通信
同步
临界点
wait ( )
notify ( ) notifyAll ( )
生产者
shop ( ) ;
消费者
buy ( ) ;
超市
货架 max = 50 ;
size = 0 ;
数组集合;
synchronized buy ( ) {
while ( size == 0 ) {
wait ( ) ;
}
nofifyAll ( ) ;
消费 size-- ;
}
synchronized shop ( ) {
while ( size == max) {
wait ( ) ;
}
nofifyAll ( ) ;
生产 size++ ;
}
2. 网络Socket
2.1 InetAddress
2.2 Port 0~65535
2.3 UDP - 无连接、不可靠
发送端
DatagramSocket ds = new DatagramSocket ( 12345 ) ;
InetAddress. getByName ( "发送机器" ) ;
DatagramPacket dp = new DatagramPacket ( byte [ ] , 0 , length, InetAddress, 端口) ;
ds. send ( dp) ;
ds. close ( ) ;
接收端
DatagramSocket ds = new DatagramSocket ( 数据报包发送的端口一致) ;
byte [ ] bs = new Byte [ 2048 ] ;
DatagramPacket dp = new DatagramPacket ( bs, length) ;
ds. recive ( dp) ;
byte [ ] data = dp. getData ( ) ;
in length = dp. getLength ( ) ;
ds. close ( ) ;
2.4 TCP - 连接、可靠
服务端
ServerSocket server = new ServerSocker ( port) ;
Socket socket = server. accept ( ) ;
客户端
Socket socket = new Sokcet ( “服务器地址”, port) ;
socket. getInputStream ( ) ;
sokcet. getOutputStream ( ) ;
3. 枚举enum
public enum Season {
SPRING, SUMMER, FALL, WINTER;
}
public enum Week {
MON ( "周一" ) ,
TUE ( "周二" ) ;
private String name;
private Week ( String name) {
this . name = name;
}
public String getName ( ) {
return name;
}
}
Season. FALL;
4. 反射
不通过new 构造器方式, 实现动态 - 操作
Class
1 :对象名. getClass ( ) ;
2 :类名. class ;
3 :Class. forName ( "包.类" ) ;
Constrcutor
Method
Field
Annotation
@Retention ( RetentionPolicy. RUNTIME) CLASS SOURCE
@Target ( ElementType. FIELD) TYPE METHOD CONSTRUCTOR
public @interface Bean {
String name ( ) ;
}