一、线程与进程
1. 线程:线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。
简单理解为:应用软件中互相独立,可以同时运行的功能。
2. 进程:进程是程序的基本执行实体。
二、多线程的应用场景
1. 软件中的耗时操作:
1)拷贝、迁移大文件
2)加载大量的资源文件
2. 所有的聊天软件
3. 所有的后台服务器
三、并发和并行
1. 并发:在同一时刻,有多个指令在单个CPU上 交替 执行。
并发编程 使我们可以将程序划分为多个分离的、独立运行的任务。通过多线程机制,这些独立任务(子任务)中的每一个都将由执行线程来驱动。
2. 并行:在同一时刻,有多个指令在多个CPU上 同时 执行。
并发和并行是有可能同时都在发生的。
四、多线程的实现方式
(一)继承Thread类的方式进行实现
public class MyThread extends Thread{
// 重写Thread类的run()方法
@Override
public void run() {
// 书写线程要执行的代码
......
}
}
public class ThreadDemo extends Thread{
public static void main(String[] args) {
MyThread t1 = new MyThread();
// 开启线程,调用start()方法
t1.start();
}
}
(二)实现Runnable接口的方式进行实现
public class MyRun implements Runnable{
@Override
public void run() {
// 书写线程要执行的代码
for (int i = 0; i < 100; i++) {
// 获取到当前线程的对象
Thread t = Thread.currentThread();
System.out.println(t.getName() + "HelloWorld!");
// 链式编程
System.out.println(Thread.currentThread().getName() + "HelloWorld!");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
// 创建MyRun的对象
// 表示多线程要执行的任务
MyRun m1 = new MyRun();
// 创建线程对象
Thread t1 = new Thread(m1);
// 给线程设置名字
t1.setName("线程1");
// 开启线程
t1.start();
}
}
(三)利用Callable接口和Future接口方式实现
特点:可以获取到多线程运行的结果
public class MyCallable implements Callable<Integer> {
@Override
// 重写call()方法
public Integer call() throws Exception {
// 求1-100之间的和
int sum = 0;
for (int i = 1; i < 100; i++) {
sum = sum + i;
}
return sum;
}
}
public class ThreadDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建MyCallable的对象(表示多线程要执行的任务)
MyCallable mc = new MyCallable();
// 创建FutureTask的对象(管理多线程运行的结果)
FutureTask<Integer> ft = new FutureTask<>(mc);
// 创建Thread类的对象
Thread t1 = new Thread(ft);
// 启动线程
t1.start();
// 获取多线程运行的结果
Integer result = ft.get();
System.out.println(result);
}
}