官方文档API

概念

程序 -> 一组静态的代码
进程 -> 正在进行的程序,静态代码运行起来
线程 -> 正在执行的程序中的小单元

1、主线程 (系统线程)
2、用户线程 -> main
3、守护线程(精灵) -> GC

状态

  • 创建
    new Thread

  • 就绪
    start()

  • 执行
    CPU分配调用run()

  • 等待/挂起
    wait()

  • 恢复到 -> 就绪状态
    notify/notifyAll

  • 异常/死亡
    exception/over

实现原理

实现线程的过程:

1、描述一个类
2、继承父类 Thread
3、重写 run()
4、new 线程对象,调用 start(),让线程进入就绪状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

public class RunningMan extends Thread{
private String name;
public RunningMan(){};
public RunningMan(String name){
this.name = name;
}
public void setName(String name){
this.name = name;
}

public void run(){
for(int i=1; i<100; i++){
System.out.println(this.name + "跑到第" + i + "米");
}
}
}

public static void main(String[] args){

RunningMan r1 = new RunningMan("苏炳添");
RunningMan r2 = new RunningMan("博尔特");
RunningMan r2 = new RunningMan("加特林");

r1.start();
r2.start();
r3.start();
}

实现线程的第二种方法(避免单继承)

1、描述一个类
2、实现一个父接口 Runnable
3、重写 run()
4、new 线程对象,调用 start(),让线程进入就绪状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

public class RunningMan implements Runnable{
private String name;
public RunningMan(){};
public RunningMan(String name){
this.name = name;
}
public void setName(String name){
this.name = name;
}

public void run(){
for(int i=1; i<100; i++){
System.out.println(this.name + "跑到第" + i + "米");
}
}
}

public static void main(String[] args){

RunningMan r1 = new RunningMan("苏炳添");
RunningMan r2 = new RunningMan("博尔特");
RunningMan r2 = new RunningMan("加特林");

new Thread(r1).start();
new Thread(r2).start();
new Thread(r3).start();
}

线程安全

synchronized 关键字,一旦被锁定,不释放的情况,其他对象都需要等待 -> “死锁”

1、放在方法的结构上
2、放在方法(构造方法、快)的内部

1
2
3
4
5
6
7
8
9
10
// 锁定的是调用该方法时的对象
publicsynchronized void get(){}

public void get(){
// ...
synchronized(对象){
// ...
}
// ...
}

Thread 常用方法

sleep、setPriority、getPriority、join

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ThreadO extends Thread{
public void run(){
//...
ThreadT tt = new ThreadT();
tt.start();
tt.join(millis:2000);
}
}

public class ThreadT extends Thread{
public void run(){ //...}
}

public static void main(String[] args){
ThreadO to = new ThreadO();
to.start();
}
死锁:增加时间差

定时器 Timer

timer.schedule();