多线程
我们学习线程之前,先进行了解进程
因为线程要依赖于进程而存在,没有进程,也就谈不上线程。
进程:正在运行的应用程序(QQ,微信 ,IDEA 浏览器)
我们现在的计算机,支持多进程的,可以运行多个进程。
QQ音乐,魔兽游戏 csgo等。 你在操作时,会感觉到这两个进程在同时进行,我会感觉一边听歌,一边玩游戏,是同时在进行的。
我们的计算机在同一个时间点上,是同时执行多个进程吗?不是,我们的(单核CPU)CPU在同一个时间点上只能执行一个进程。
你的感觉多个进程在同时执行,那是因为CPU在多个进程间进行一个高速的切换执行,你的人耳和眼睛根本就感觉不到。
我们的进程开启后,会执行很多的任务,那这个每一个执行的任务,就称之为一个线程。
比如QQ音乐开启后,其实就是一个进程,QQ音乐运行后,歌词的下载(任务1)歌曲的音频解码(任务2) 一个进程里面可以包含多个线程,当然一个进程里面你至少有一个线程。
进程是拥有资源的基本单位,线程是CPU调度的基本单位。
多线程的意义是什么?提高应用程序,对CPU的使用率。
并发:值的的是多个任务,高速的交替执行。(因为高速的切换,你可能会感觉是多个任务同时执行。)
并行:多个任务同时执行。
Java给我们提供好了一个类 Thread 通过这个类,进创建线程,和开启线程。线程 是程序中的执行线程。Java 虚拟机允许应用程序并发地运行多个执行线程。
创建新执行线程有两种方法。
方式1:
1.将一个类声明为 Thread 的子类。
2.该子类应重写 Thread 类的 run 方法。
3.接下来可以分配并启动该子类的实例。
//创建一个线程
MyThread myThread = new MyThread();
//开启线程 调用run()方法,其实子线程并没有开启,这种方式其实就是你创建了一个类的对象,调用了类中的一个 方法而已。
//myThread.run();
//正确开启一个线程的方式是调用 start();当线程开启后,由子线程去调用run()方法来执行run()方法里面的代码
myThread.start();
//线程不要重复开启 重复开启会抛异常。IllegalThreadStateException
//myThread.start();
System.out.println("主线程后面的代码");
System.out.println("主线程后面的代码");
System.out.println("主线程后面的代码");
System.out.println("主线程后面的代码");
System.out.println("主线程后面的代码");
//在这个节点处,我再开一条线程
MyThread myThread2 = new MyThread();
myThread2.start();
System.out.println("主线程后面的代码");
System.out.println("主线程后面的代码");
System.out.println("主线程后面的代码");
}
}
run 方法里面写的代码就是,将来让这个子线程来执行的代码,一般来说我们会把一些耗费时间的代码让子线程来操作, 而不会写到主线程,去阻塞主线程,来提高用户的体验。
方式2:
1.自定义一个类,继承Thread类
2.创建该子类对象,重写run()方法
3.调用start()方法来开启线程
public class MyThread extends Thread{
//run()方法是让线程来调用的方法
@Override
public void run() {
//子线程就是一般用来处理耗时操作的代码,
//模拟耗时操作
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
MyThread th = new MyThread();
th.start();
//th.start(); 不要重复开启同一个线程对象
System.out.println("主线程后面的代码");
MyThread th2 = new MyThread();
th2.start();
}
}
以上为单线程演示,但是到了多线程中,因为并发执行需要抢占CPU资源,此处那个线程抢到,那个线程先执行(抢到一次,执行一下),线程的执行过程具有随机性。我们启动线程使用不是run方法,而应该是start方法.使该线程开始执行;
Java 虚拟机调用该线程的 run 方法。 为什么要重写run方法?这个类是一个线程类,那么在这个类中我们可不可以写一些其他的方法呢? 我们可以在写其他的方法,那么其他方法中封装的代码都是需要被我们线程执行的吗? 那么也就是run方法中封装应该是必须被线程执行的代码.
run方法中的代码的书写原则: 一般是比较耗时的代码
public class MyThread extends Thread{
@Override
public void run() { //th1 th2
for (int i = 0; i < 100; i++) {
System.out.println("线程:"+this.getName()+":"+i);
}
}
}
Thread thread = Thread.currentThread();
thread.setName("主线程");
String name = thread.getName();
System.out.println(name);
MyThread th1 = new MyThread();
MyThread th2 = new MyThread();
MyThread th3 = new MyThread();
th1.setName("哈哈哈");
th2.setName("呵呵呵");
th3.setName("六六六");
th1.start();
th2.start();
th3.start();
}
}
currentThread(); 获取当前执行的线程对象
Thread thread = Thread.currentThread();
thread.setName("主线程");
String name = thread.getName();
System.out.println(name);
MyThread th1 = new MyThread();
MyThread th2 = new MyThread();
MyThread th3 = new MyThread();
th1.setName("111");
th2.setName("222");
th3.setName("333");
th1.start();
th2.start();
th3.start();
}
}
线程中的文件复制
public class CopyTextThread extends Thread{
@Override
public void run() {
try {
FileInputStream in2 = new FileInputStream("MyTest.java");
FileOutputStream out2 = new FileOutputStream("C:\\Users\\ShenMouMou\\Desktop\\MyTest.java");
int len2 = 0;
byte[] bytes2 = new byte[100];
while ((len2 = in2.read(bytes2)) != -1) {
out2.write(bytes2, 0, len2);
out2.flush();
}
in2.close();
out2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class CopyVideoThread extends Thread{
@Override
public void run() {
try {
// E:\课堂录制视频\Rec 2020 - 05 - 31 0001. mp4
FileInputStream in = new FileInputStream("E:\\课堂录制视频\\Rec 2020-05-31 0001.mp4");
FileOutputStream out = new FileOutputStream("C:\\Users\\ShenMouMou\\Desktop\\001.mp4");
int len = 0;
byte[] bytes = new byte[100];
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
//复制一首歌,一个视频
System.out.println("进程开始");
CopyVideoThread th1 = new CopyVideoThread();
th1.start();
CopyTextThread th2 = new CopyTextThread();
th2.start();
System.out.println("主线程下面的代码");
System.out.println("主线程下面的代码");
System.out.println("主线程下面的代码");
System.out.println("主线程下面的代码");
}
}
线程的执行
假如我们的计算机只有一个 CPU,那么 CPU 在某一个时刻只能执行一条指令。
线程有两种调度模型:
分时调度模型 :所有线程轮流使用 CPU 的使用权,平均分配每个线程占用 CPU 的时间片。
抢占式调度模型 :优先让优先级高的线程使用 CPU,如果线程的优先级相同,那么会随机选择一个,优先级高的线程获取的 CPU 时间片相对多一些。Java使用的是抢占式调度模型。
MyThread th1 = new MyThread();
MyThread th2 = new MyThread();
MyThread th3 = new MyThread();
//设置线程的优先级 范围1--10
th1.setPriority(1);
th2.setPriority(2);
th3.setPriority(Thread.MAX_PRIORITY);
//多个线程并发执行()多个抢占CPU的执行权,哪个线程抢到,在某一个时刻,就会执行哪个线程。线程的执行具有随机性。
//获取线程的优先级
int priority1 = th1.getPriority();
int priority2 = th2.getPriority();
int priority3= th3.getPriority();
//线程默认的优先级是5
//
System.out.println("线程的优先级"+ priority1);
System.out.println("线程的优先级" + priority2);
System.out.println("线程的优先级" + priority3);
//Thread.MAX_PRIORITY;
//Thread.MIN_PRIORITY;
//Thread.NORM_PRIORITY
th1.setName("范冰冰");
th2.setName("刘亦菲");
th3.setName("张曼玉");
th1.start();
th2.start();
th3.start();
}
}
线程的休眠
通过sleep方法让正在工作的线程进行指定时间的停止。
public class MyThread extends Thread{
public MyThread(){}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(500); //单位是毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
String name1 = Thread.currentThread().getName();
System.out.println(name1 + "===" + i);
}
}
}
public static void main(String[] args) throws InterruptedException {
//
System.out.println("主线程启动");
Thread.sleep(2000);
System.out.println("主线程执行");
MyThread th1 = new MyThread("A线程");
MyThread th2 = new MyThread("B线程");
th1.start();
th2.start();
}
}
//此处,如果A线程先抢到了执行权,那么它会停止0.5秒,在执行。
加入线程
public final void join ()
意思就是:等待该线程执行完毕了以后, 其他线程才能再次执行
注意事项:
在线程启动之后, 在调用方法
join ()可以让多个线程并发执行,变成串行(挨个排队执行,不用抢)
public class MyThread extends Thread{
public MyThread(){}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i <2000; i++) {
String name1 = Thread.currentThread().getName();
Thread.yield();//线程礼让
System.out.println(name1 + "===" + i);
}
}
}
MyThread th1 = new MyThread();
MyThread th2 = new MyThread();
MyThread th3 = new MyThread();
th1.setName("刘备");
th2.setName("关羽");
th3.setName("张飞");
th1.start();
//注意:在线程启动之后, 再调用join()方法
th1.join();
th2.start();
th2.join();
th3.start();
th3.join();
}
}
守护线程
设置为守护线程 当主线程死亡后,守护线程要立马死亡掉。
注意:setDaemon(true)该方法必须在启动线程前调用。
public class MyTest {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().setName("刘备:主线程");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"=="+i);
}
MyThread th1 = new MyThread();
MyThread th2 = new MyThread();
th1.setName("张飞");
th2.setName("关羽");
//注意:setDaemon(true)该方法必须在启动线程前调用。
th1.setDaemon(true);
th2.setDaemon(true);
th1.start();
th2.start();
System.out.println(Thread.currentThread().getName()+"退出了");
}
}
创建线程的第二种方式
- 定义一个类实现 Runnable 接口。
- 重写该接口 run 方法。
- 然后可以分配该类的实例,
- 在创建 Thread 对象时作为一个参数来传递并启动。
这种方式扩展性强 实现一个接口 还可以再去继承其他类
MyRunnable myRunnable = new MyRunnable();
Thread th1 = new Thread(myRunnable);
th1.setName("A线程");
th1.start();
Thread th2 = new Thread(new MyRunable2());
th2.setName("B线程");
th2.start();
Thread(Runnable target, String name):分配新的 Thread 对象。
MyRunable myRunable = new MyRunable();
Thread th1 = new Thread(myRunable, "A线程");
Thread th2 = new Thread(myRunable, "B线程");
th1.start();
th2.start();
创建线程的第三种方式
实现步骤
1. 创建一个类实现Callable 接口 重写接口中的call方法
2. 建一个FutureTask类将Callable接口的子类对象作为参数传进去
3. 创建Thread类, 将FutureTask对象作为参数传进去
4. 开启线程
//我们有一种需求:当子线程执行完,我想获取子线程执行完之后的结果。
MyCallable myCallable = new MyCallable(100);
FutureTask<Integer> task = new FutureTask<>(myCallable);
Thread th = new Thread(task);
th.start();
//获取线程执行完之后返回的结果
Integer integer = task.get();
System.out.println(integer);
MyCallable myCallable2 = new MyCallable(1000);
FutureTask<Integer> task2 = new FutureTask<>(myCallable2);
Thread th2 = new Thread(task2);
th2.start();
Integer integer1 = task2.get();
System.out.println(integer1);
//Runnable 任务 让线程来执行 run() 没有返回值,这个方法不能抛出异常,只能抓
//Callable 任务 让线程来执行 call() 有返回值,而且可以抛出异常。
}
}
public class MyCallable implements Callable<Integer> {
private int num;
public MyCallable(int num) {
this.num = num;
}
//call()方法 让线程来执行的方法
@Override
public Integer call() throws Exception {
//System.out.println("线程执行了此代码");
//求1-num之间的和
int sum=0;
for (int i = 1; i <= num; i++) {
sum+=i;
}
return sum;
}
}