1. 什么是线程
线程(英语:thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。在Unix System V及SunOS中也被称为轻量进程(lightweight processes),但轻量进程更多指内核线程(kernel thread),而把用户线程(user thread)称为线程。
线程是独立调度和分派的基本单位。线程可以为操作系统内核调度的内核线程,如Win32线程;由用户进程自行调度的用户线程,如Linux平台的POSIX Thread;或者由内核与用户进程,如Windows 7的线程,进行混合调度。
同一进程中的多条线程将共享该进程中的全部系统资源,如虚拟地址空间,文件描述符和信号处理等等。但同一进程中的多个线程有各自的调用栈(call stack),自己的寄存器环境(register context),自己的线程本地存储(thread-local storage)。
一个进程可以有很多线程,每条线程并行执行不同的任务。
在多核或多CPU,或支持Hyper-threading的CPU上使用多线程程序设计的好处是显而易见,即提高了程序的执行吞吐率。在单CPU单核的计算机上,使用多线程技术,也可以把进程中负责I/O处理、人机交互而常被阻塞的部分与密集计算的部分分开来执行,编写专门的workhorse线程执行密集计算,从而提高了程序的执行效率。
2. 线程的生命周期
3. java中实现多线程的三种方式
1. 继承Thread类并重写run方法
public class MyThread extends Thread{
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(this.getName() + "running");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();
}
}
// 执行结果
Thread-1running
Thread-0running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
2. 实现Runnable接口并重写run方法
public class MyThread2 implements Runnable{
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "running");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread2 myThread1 = new MyThread2();
MyThread2 myThread2 = new MyThread2();
new Thread(myThread1).start();
new Thread(myThread2).start();
}
}
// 执行结果
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-1running
Thread-0running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
Thread-1running
Thread-0running
Thread-0running
Thread-1running
Thread-0running
Thread-1running
3. 实现Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyThread3 implements Callable<String> {
@Override
public String call() throws Exception {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "running");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return Thread.currentThread().getName() + "执行完毕~";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread3 task1 = new MyThread3();
MyThread3 task2 = new MyThread3();
MyThread3 task3 = new MyThread3();
// 创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
// 提交执行
Future<String> r1 = service.submit(task1);
Future<String> r2 = service.submit(task2);
Future<String> r3 = service.submit(task3);
// 获取返回值
String rs1 = r1.get();
String rs2 = r2.get();
String rs3 = r3.get();
System.out.println("rs1:" + rs1);
System.out.println("rs2:" + rs2);
System.out.println("rs3:" + rs3);
// 关闭服务
service.shutdownNow();
}
}
// 执行结果
pool-1-thread-3running
pool-1-thread-1running
pool-1-thread-2running
pool-1-thread-3running
pool-1-thread-2running
pool-1-thread-1running
pool-1-thread-2running
pool-1-thread-1running
pool-1-thread-3running
pool-1-thread-2running
pool-1-thread-3running
pool-1-thread-1running
pool-1-thread-2running
pool-1-thread-3running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-3running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-3running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-2running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-2running
pool-1-thread-1running
pool-1-thread-3running
pool-1-thread-1running
pool-1-thread-2running
rs1:pool-1-thread-1执行完毕~
rs2:pool-1-thread-2执行完毕~
rs3:pool-1-thread-3执行完毕~
4. 使用线程池(推荐使用)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThread4 {
public static void main(String[] args) {
// 创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new RunnableThread());
service.execute(new RunnableThread());
service.execute(new RunnableThread());
// 关闭连接
service.shutdownNow();
}
}
class RunnableThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName() + "running");
}
}
// 执行结果
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-2running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-3running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-1running
pool-1-thread-2running
pool-1-thread-2running
小结
- 继承Thread类
(1) 子类继承Thread类具备多线程能力
(2) 启动线程:子类对象.start()
(3)不建议使用:避免OOP单继承局限性
- 实现Runnable接口
(1) 实现Runnable具有多线程能力
(2) 启动线程:传入目标对象+Thread对象.start()
(3)推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
- 实现Callable接口
(1) 可以定义返回值
(2) 可以抛出异常
(3) 启动线程方式比较麻烦 - 使用线程池
(推荐使用)
(1) 提高响应速度(减少了创建新线程的时间)
(2) 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
(3) 便于线程管理(…)
corePollSize: 核心池的大小
maximumPoolSize: 最大线程数
keepAliveTime: 线程没有任务时最多保持多长时间后会终止