学习视频参考链接:https://www.bilibili.com/video/BV1V4411p7EF?p=27
1、线程简介
栈空间操作起来最快但是栈很小,通常大量的对象都是放在堆空间,栈和堆的大小都可以通过 JVM 的启动参数来进行调整,栈空间用光了会引发 StackOverflowError,而堆和常量池空间不足则会引发 OutOfMemoryError。
String str = new String(“hello”);
上面的语句中变量 str 放在栈上,用 new 创建出来的字符串对象放在堆上,而 “hello” 这个字面量是放在方法区的。
例子:吃饭 + 玩手机
这些动作都可以抽象为任务,虽然看起来一心二用,但人只有一个大脑,在一个时间片刻只能处理一个任务。
CPU 也是一样,面对多个任务,只能在一个时间片刻处理一个任务。
线程调用 run 方法和调用 start 方法开启子线程的区别如下图所示。
- 线程就是独立的执行路径;
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,GC 线程;
- main()称之为主线程,为系统的入口,用于执行整个程序;
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预。
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制;
- 线程会带来额外的开销,如 CPU 调度时间,并发控制开销。
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
2、线程实现
线程的三种实现方式
2.1 继承 Thread 类,重写 run 方法
继承 Thread 类,重写 run 方法。创建这个类的对象,再调用 start() 即可
public class ThreadTest {
// 继承 Thread 类并重写 run 方法
public static class MyThread extends Thread{
@Override
public void run() {
System.out.println("I am a child thread");
}
}
public static void main(String[] args) {
//创建一个线程
MyThread thread = new MyThread();
//启动线程
thread.start();
}
}
下载文件需要在 pom.xml 中 commons io 包。
使用该方法下载网络图片。
引入资源
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
public class TestThread2 extends Thread{
// 网络图片地址
private String url;
// 保存的文件名
private String name;
public TestThread2(String url,String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
// 进入线程后,会创建一个下载器,下载器通过 downloader 方法,传入 url 和 name 下载相应的资源
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:"+ name);
}
public static void main(String[] args) {
// 这是 TestThread2 类的主方法
// 创建三个继承 Thread 的子类
TestThread2 test01 = new TestThread2("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3796445054,4193265240&fm=26&gp=0.jpg", "test01");
TestThread2 test02 = new TestThread2("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454961548&di=c3b49cc5869f058a6cded1434ea56f85&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F5%2F538ec3134b63b.jpg", "test02");
TestThread2 test03 = new TestThread2("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2044644877,1766802492&fm=15&gp=0.jpg", "test03");
// 并开启线程
test01.start();
test02.start();
test03.start();
}
}
//下载器,这是一个类
class WebDownloader{
// 下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader 方法出现问题");
}
}
}
2.2 实现 Runnable 接口,创建 Tread 对象
实现Runnable 接口,创建 Tread 对象,传入实现类,开启 start 方法.
public class ThreadRunnableTest {
public static class MyThread implements Runnable {
@Override
public void run() {
System.out.println("I am a child thread --Runnable");
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
new Thread(thread).start();
new Thread(thread).start();
}
}
继承 Thread 类
子类继承 Thread 类具备多线程能力
启动线程:子类对象 .start()
不建议使用:避免 OOP 单继承局限性
实现 Runnable 接口
实现接口 Runnable 具有多线程能力
启动线程:传入目标对象+Thread对象.start()
推荐使用:避免单继承局限性,方便同一个对象被多个线程使用。
火车抢票实例:
Runnable 实现多线程,创造一个实列 ticketRunnable ,可共享给多个线程。
// 发现问题:多个线程操作同一个资源,线程不安全,数据紊乱!
public class TicketRunnable implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums<=0){
break;
}
// 模拟延时
/*
IllegalArgumentException
if the value of {@code millis} is negative, or the value of
{@code nanos} is not in the range {@code 0-999999}
InterruptedException
if any thread has interrupted the current thread. The
<i>interrupted status</i> of the current thread is
cleared when this exception is thrown.
*/
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketNums--;
System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums+"票");
}
}
public static void main(String[] args) {
// 实现了 Runnable 接口的类,创建其实例
TicketRunnable ticketRunnable = new TicketRunnable();
// ticketRunnable 实例可用于多个线程,其中的资源被共享。
new Thread(ticketRunnable,"01小明+++++").start();
new Thread(ticketRunnable,"02老师-----").start();
new Thread(ticketRunnable,"03黄牛=====").start();
}
}
03黄牛=====-->拿到了第8票
01小明+++++-->拿到了第8票
02老师------->拿到了第8票
03黄牛=====-->拿到了第7票
02老师------->拿到了第7票
01小明+++++-->拿到了第7票
02老师------->拿到了第6票
03黄牛=====-->拿到了第6票
01小明+++++-->拿到了第6票
01小明+++++--