基础知识

1:多线程实现方式

1:承Thread类,重写run函数

  1. class Uio extends Thread{
  2. static HashSet<Integer> a = new HashSet<>();
  3. int o
  4. Uio(int o,String name){
  5. super(name)
  6. this.o = o
  7. }
  8. public void run(){
  9. println(this.o)
  10. println(currentThread().getName())
  11. for (int i = 0; i <5000 ; i++) {
  12. synchronized (this.class){
  13. def add = a.add(i)
  14. }
  15. }
  16. }
  17. }

2:实现Runnable接口,重写run函数

  1. class A implements Runnable{
  2. @Override
  3. void run() {
  4. ...
  5. }
  6. }

因 Thread 实现了 Runnable 所以两个类似,Runnable 是函数式接口,可以简写

  1. Thread thread = new Thread(
  2. {
  3. IntStream.range(0,100).each {
  4. System.out.println(it)
  5. }
  6. }
  7. )
  8. thread.start()
  9. 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(runnable, null)}

  1. FutureTask task = new FutureTask<>(new Runnable(){
  2. @Override
  3. void run() {
  4. println(1)
  5. }
  6. },"123") // 不需要返回值可以null
  7. Thread thread = new Thread(task,"线程一")
  8. thread.start()
  9. thread.join()
  10. println(task.get())

3:实现Callable接口,重写call函数 需要 FutureTask 转换成 runnable 再用 Thread装载 运行

  1. class A implements Callable {
  2. @Override
  3. Object call() throws Exception {
  4. ...
  5. }
  6. }

或者

  1. Callable callable = new Callable(){
  2. @Override
  3. Object call() throws Exception {
  4. return 1
  5. }
  6. }
  7. FutureTask task= new FutureTask(callable)
  8. def thread = new Thread(task,"1234")
  9. thread.start()
  10. thread.join()
  11. 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 接口实现,可自由配置 | |

线程的几种状态

  1. * Possible state transitions:
  2. * NEW -> COMPLETING -> NORMAL
  3. * NEW -> COMPLETING -> EXCEPTIONAL
  4. * NEW -> CANCELLED
  5. * NEW -> INTERRUPTING -> INTERRUPTED
  6. */
  7. private volatile int state;
  8. private static final int NEW = 0;
  9. private static final int COMPLETING = 1;
  10. private static final int NORMAL = 2;
  11. private static final int EXCEPTIONAL = 3;
  12. private static final int CANCELLED = 4;
  13. private static final int INTERRUPTING = 5;
  14. private static final int INTERRUPTED = 6;

2: join 与 deman

1:join

同步线程: 等待线程执行完毕

2:daemon 守护线程

守护线程会在所有非守护线程结束后强行结束
必须在strat前set

进阶:

2:线程池

3:threadlocal