基础知识
1:多线程实现方式
1:承Thread类,重写run函数
class Uio extends Thread{
static HashSet<Integer> a = new HashSet<>();
int o
Uio(int o,String name){
super(name)
this.o = o
}
public void run(){
println(this.o)
println(currentThread().getName())
for (int i = 0; i <5000 ; i++) {
synchronized (this.class){
def add = a.add(i)
}
}
}
}
2:实现Runnable接口,重写run函数
class A implements Runnable{
@Override
void run() {
...
}
}
因 Thread 实现了 Runnable 所以两个类似,Runnable 是函数式接口,可以简写
Thread thread = new Thread(
{
IntStream.range(0,100).each {
System.out.println(it)
}
}
)
thread.start()
thread.join()
FauterTask 提供 构造函数 转换 Runable-> callable,所以也可以这么写,使得Runnable 能返回值,如果不需要可以直接为null
源码解释
* @param result the result to return on successful completion. If
you don’t need a particular result, consider using
constructions of the form:
* {@code Future<?> f = new FutureTask
FutureTask task = new FutureTask<>(new Runnable(){
@Override
void run() {
println(1)
}
},"123") // 不需要返回值可以null
Thread thread = new Thread(task,"线程一")
thread.start()
thread.join()
println(task.get())
3:实现Callable接口,重写call函数 需要 FutureTask 转换成 runnable 再用 Thread装载 运行
class A implements Callable {
@Override
Object call() throws Exception {
...
}
}
或者
Callable callable = new Callable(){
@Override
Object call() throws Exception {
return 1
}
}
FutureTask task= new FutureTask(callable)
def thread = new Thread(task,"1234")
thread.start()
thread.join()
println(task.get())
4:几种方法对比
方法 | Thread | Runnable | Callable | |
---|---|---|---|---|
方式 | 继承,重写run | 实现run | 实现 call | |
运行方式 | 直接start | 装配 到 Thread | FutureTask 转换成 Runnable 装配 到 Thread | |
是否有返回值 | X | X | - [x] |
| |
| 是否能抛异常 | X | X |
- [x]
| | | 简单 | 1 啥都不用管,重写run 运行,功能齐全 | 同 Callable,也可以通过 FutureTask转换,从而获得一些能力 | 3 要 FutureTask 转换 装配 到 Thread 运行 | | | 灵活 | 3 要继承类,只能单继承 | 1:Thread 类接收一个闭包函数,可以灵活装配 ,比callable少了FutureTask 转换 | 2 接口实现,可自由配置 | |
线程的几种状态
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int NORMAL = 2;
private static final int EXCEPTIONAL = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTING = 5;
private static final int INTERRUPTED = 6;
2: join 与 deman
1:join
同步线程: 等待线程执行完毕
2:daemon 守护线程
守护线程会在所有非守护线程结束后强行结束
必须在strat前set