4-1-2-多线程脑图和四种线程创建

文章目录
  1. 1. java多线程脑图
  2. 2. 四种线程创建
    1. 2.1. 1.继承thread类(thread类实现了runnable接口)
      1. 2.1.1. 启动线程的唯一方法就是通过 Thread 类的 start()实例方法。start()方法是一个 native 方法,它将启动一个新线程,并执行 run()方法
    2. 2.2. 2.实现runnable接口(继承只能一个,实现可以多个)
    3. 2.3. 3.executorService, callable, future有返回值线程
    4. 2.4. 4.基于线程池(不用每次创建,可以缓存连接)Executors.newFixedThreadPool

java多线程脑图

image-20210702114747022

四种线程创建

1.继承thread类(thread类实现了runnable接口)

启动线程的唯一方法就是通过 Thread 类的 start()实例方法。start()方法是一个 native 方法,它将启动一个新线程,并执行 run()方法

1
2
3
4
5
6
7
public class MyThread extends Thread { 
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread1 = new MyThread();
myThread1.start();

2.实现runnable接口(继承只能一个,实现可以多个)

1
2
3
4
5
6
7
8
9
10
public class MyThread extends OtherClass implements Runnable { 
public void run() {
System.out.println("MyThread.run()");
}
}

//启动 MyThread,需要首先实例化一个 Thread,并传入自己的 MyThread 实例:
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();

3.executorService, callable, future有返回值线程

  1. 执行Callable 任务后,可以获取一个 Future 的对象
  2. 在该对象上调用 get 就可以获取到 Callable 任务返回的 Object 了
  3. 再结合线程池接口 ExecutorService 就可以实现传说中有返回结果的多线程了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//1.创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 2.创建多个有返回值的任务
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable(i + " ");
// 3.执行任务并获取 Future 对象
Future f = pool.submit(c);
list.add(f);
}
// 4.关闭线程池
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 5.从 Future 对象上获取任务的返回值,并输出到控制台
System.out.println("res:" + f.get().toString());
}

4.基于线程池(不用每次创建,可以缓存连接)Executors.newFixedThreadPool

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
while(true) {
threadPool.execute(new Runnable() { // 提交多个线程任务,并执行
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running ..");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
} }