【Java基础】-- 第15章:多线程基础

Java基础

十五、多线程基础

线程介绍

程序

是为完成特定任务、用某种语言编写的一组指令的集合,简单的说:就是我们写的代码

进程

  • 进程是指运行中的程序,如我们使用的QQ,就启动了一个进程,操作系统就会为该进程分配内存空间
  • 进程是程序的一次执行过程,或是正在运行的一个程序,是动态过程:有它自己的产生、存在和消亡的过程

线程

  • 线程是由进程创建的,是进程的一个实体
  • 一个进程可以拥有多个线程

单线程

同一时刻,只允许执行一个线程

多线程

同一时刻,可以执行多个线程,如:一个qq进程,可以同时打开多个聊天窗口

并发

同一时刻,多个任务交替执行,造成一种"貌似同时"的错觉,简单的说,单核cpu实现的多任务就是并发

并行

同一时刻,多个任务同时执行,多核cpu可以实现并行

线程基本使用

创建线程的两种方式
  • 继承Thread类,重写run方法
  • 实现Runnable接口,重写run方法

image-20221031111144683

线程应用案例–继承Thread类

image-20221031133858670

package com.Chapter10.Thread_;

import sun.util.resources.cldr.aa.CurrencyNames_aa;

public class thread01 {
    public static void main(String[] args) throws InterruptedException {
        //创建一个Cat对象,可以当作线程使用
        Cat cat = new Cat();
        cat.start();  //启动线程
        //说明:当main线程启动一个线程Thread-0,主线程不会阻塞,会继续执行
        //这时主线程和子线程是交替执行
        System.out.println("主线程继续指向" + Thread.currentThread().getName());
        for(int i = 0;i < 10;i++){
            System.out.println("主线程i=" + i);
            //让主线程休眠
            Thread.sleep(1000);
        }
    }
}
//1.当一个类继承了Thread类,该类就可以当作线程使用
//2.我们会重写run方法,写上自己的代码
//3.run Thread类实现了Runnable接口的run方法
/*
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
 */
class Cat extends Thread{
    int times = 0;
    @Override
    public void run() { //重写run方法
        while(true){
            //该线程每隔1秒,在控制台输出
            System.out.println("Java" + (++times)+ Thread.currentThread().getName());
            //让线程休眠1秒
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(times == 80)
                break; //当times等于80,就退出线程
        }
    }
}
run方法和start方法

image-20221031134530536

image-20221031134417544

线程应用案例- 实现Runnable接口

1)java是单继承的,在某些情况下一个类可能已经继承了某个父类,这时在用继承Thread类方法来创建线程显然是不可能的了

2)Java设计者提供了另一种方法来创建线程,就是通过实现Runnable接口来创建线程

image-20221031140837874

package com.Chapter10.Thread_;

import sun.awt.windows.ThemeReader;

import java.util.function.DoublePredicate;

public class thread02 {
    public static void main(String[] args) {
//        Dog dog = new Dog();
//        //不能调用start
//        //dog.start();
//
//        //创建了Thread对象,把dog对象(实现Runnable),放入Thread
//        Thread thread = new Thread(dog);
//        thread.start();
//    }
        Tiger tiger = new Tiger();
        ThreadProxy threadProxy = new ThreadProxy(tiger);  //这里可以传入tiger是因为ThreadProxy传入的Runnable,而tiger继承Runnable
        threadProxy.start();

    }
}
class Animal{}
class Tiger extends Animal implements Runnable{

    @Override
    public void run() {
        System.out.println("老虎大叫...");
    }
}
//线程代理类
class ThreadProxy implements Runnable{
    private Runnable target = null; //属性,类型是Runnable

    @Override
    public void run() {
        if(target!=null){
            target.run(); //动态绑定,运行类型是传入的Tiger,所以最终返回老虎大叫
        }
    }
    public ThreadProxy(Runnable target){
        this.target = target;
    }
    public void start(){
        start0();  //真正实现多线程
    }
    public void start0() {
        run();
    }

}


class Dog implements Runnable{

    int count = 0;
    @Override
    public void run() {
        while(true){
            System.out.println("hhhh" + (++count) + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
线程应用案例-多线程执行

image-20221031140949506

package com.Chapter10.Thread_;

//main线程启动两个子线程
public class thread03 {
    public static void main(String[] args) {
        T1 t1 = new T1();
        T2 t2 = new T2();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);
        thread1.start();
        thread2.start();
    }

}
class T1 implements Runnable{

    int count = 0;

    @Override
    public void run() {
        //每隔1秒输出"hello,world",输出10次
        while(true) {
            System.out.println("hello,world " + (++count));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }if(count == 10)
                break;
        }

    }
}
class T2 implements Runnable{

    int count = 0;

    @Override
    public void run() {
        //每隔1秒输出"hello,world",输出10次
        while(true){
            System.out.println("hi " + (++count));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(count == 5)
                break;
        }

    }
}

image-20221031141909965

继承Thread和实现Runnable的区别

image-20221031142139395

image-20221031143019979

package com.hspedu.ticket;
/**
* 使用多线程,模拟三个窗口同时售票100 张
*/
public class SellTicket {
    public static void main(String[] args) {
        //测试
        // SellTicket01 sellTicket01 = new SellTicket01();
        // SellTicket01 sellTicket02 = new SellTicket01();
        // SellTicket01 sellTicket03 = new SellTicket01();
        //
        // //这里我们会出现超卖..
        // sellTicket01.start();//启动售票线程
        // sellTicket02.start();//启动售票线程
        // sellTicket03.start();//启动售票线程
        System.out.println("===使用实现接口方式来售票=====");
        SellTicket02 sellTicket02 = new SellTicket02();
        new Thread(sellTicket02).start();//第1 个线程-窗口
        new Thread(sellTicket02).start();//第2 个线程-窗口
        new Thread(sellTicket02).start();//第3 个线程-窗口
    }
}
//使用Thread 方式
class SellTicket01 extends Thread {
    private static int ticketNum = 100;//让多个线程共享ticketNum
    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                break;
            }
            //休眠50 毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票"
                               + " 剩余票数=" + (--ticketNum));
        }
    }
}
//实现接口方式
class SellTicket02 implements Runnable {
    private int ticketNum = 100;//让多个线程共享ticketNum
    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                break;
            }
            //休眠50 毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票"
                               + " 剩余票数=" + (--ticketNum));//1 - 0 - -1 - -2
        }
    }
}

出现超卖的情况,线程同步问题

image-20221031143249825

image-20221031143002927

线程终止

基本介绍

1)当线程完成任务后,会自动退出

2)还可以通过使用变量来控制run方法退出的方式停止线程,即通知方式

image-20221031143459677

package com.Chapter10.Thread_;

import sun.awt.windows.ThemeReader;

public class Thread04 {
    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.start();
        //如果希望main线程去控制t1线程的终止,必须可以修改loop
        //让t退出run方法,从而终止t线程 ->通知方式

        //让主线程休眠10秒,再通知t线程退出
        Thread.sleep(10*1000);
        t.setLoop(false);
    }
}
class T extends Thread{
    //设置一个控制变量
    private boolean loop = true;

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        while(loop){
            try {
                Thread.sleep(50); //让当前线程休眠50ms
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("T运行中....");
        }

    }
}

线程常用方法

常用方法

1)setName:设置线程名称,使之与参数name相同

2)getName:返回该线程的名称

3)start:使线程开始执行,Java虚拟机底层调用该线程的start0方法

4)run:调用线程对象run方法

5)setPriority:更改线程的优先级

6)getPriority:获取线程的优先级

7)sleep:在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)

8)interrupt:中断线程

注意事项:

  • start底层会创建新的线程,调用run,run就是一个简单的方法调用,不会启动新线程

  • 线程优先级的范围

  • interrupt,中断线程,但并没有真正的结束线程,所以一般用于中断正在休眠线程

    image-20221031145443118

  • sleep:线程的静态方法,使当前线程休眠

image-20221031150547936

用户线程和守护线程

1)用户线程:也叫工作线程,当线程的任务执行完成或通知方式结束

2)守护线程:一般是为工作线程服务的,当所有的用户线程结束,守护线程自动结束

3)常见的守护线程:垃圾回收机制

image-20221031151526307

image-20221031151740683

线程的生命周期

image-20221031151856654

image-20221031152321130

Synchronized

线程同步机制

1)在多线程编程中,一些敏感数据不允许被多个线程同时访问,此时就使用同步访问技术,保证数据在任何同一时刻,最多有一个线程访问,以保证数据的完整性

2)也可以理解为:线程同步,即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对内存地址进行操作

image-20221031153150435

同步原理

image-20221031154144808

互斥锁

基本介绍:
1)Java语言中,引入了对象互斥锁的概念,来保证共享数据操作的完整性

2)每个对象都对应一个可称为"互斥锁"的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象

3)关键字synchronized来与对象的互斥锁联系,当某个对象用synchronized修饰时,表面该对象在任一时刻只能由一个线程访问

4)同步的局限性:导致程序的执行效率降低

5)同步方法(非静态的)的锁可以是this,也可以是其他对象(要求是同一个对象)

6)同步方法(静态的)的锁为当前类本身

package com.hspedu.syn;
/**
* 使用多线程,模拟三个窗口同时售票100 张
*/
public class SellTicket {
    public static void main(String[] args) {
        //测试
        // SellTicket01 sellTicket01 = new SellTicket01();
        // SellTicket01 sellTicket02 = new SellTicket01();
        // SellTicket01 sellTicket03 = new SellTicket01();
        //
        // //这里我们会出现超卖..
        // sellTicket01.start();//启动售票线程
        // sellTicket02.start();//启动售票线程
        // sellTicket03.start();//启动售票线程
        // System.out.println("===使用实现接口方式来售票=====");
        // SellTicket02 sellTicket02 = new SellTicket02();
        //
        // new Thread(sellTicket02).start();//第1 个线程-窗口
        // new Thread(sellTicket02).start();//第2 个线程-窗口
        // new Thread(sellTicket02).start();//第3 个线程-窗口
        //测试一把
        SellTicket03 sellTicket03 = new SellTicket03();
        new Thread(sellTicket03).start();//第1 个线程-窗口
        new Thread(sellTicket03).start();//第2 个线程-窗口
        new Thread(sellTicket03).start();//第3 个线程-窗口
    }
}
//实现接口方式, 使用synchronized 实现线程同步
class SellTicket03 implements Runnable {
    private int ticketNum = 100;//让多个线程共享ticketNum
    private boolean loop = true;//控制run 方法变量
    Object object = new Object();
    //同步方法(静态的)的锁为当前类本身
    //老韩解读
    //1. public synchronized static void m1() {} 锁是加在SellTicket03.class
    //2. 如果在静态方法中,实现一个同步代码块.
    /*
synchronized (SellTicket03.class) {
System.out.println("m2");
}
*/
    public synchronized static void m1() {
    }
    public static void m2() {
        synchronized (SellTicket03.class) {
            System.out.println("m2");
        }
    }
    //老韩说明
    //1. public synchronized void sell() {} 就是一个同步方法
    //2. 这时锁在this 对象
    //3. 也可以在代码块上写synchronize ,同步代码块, 互斥锁还是在this 对象
    public /*synchronized*/ void sell() { //同步方法, 在同一时刻, 只能有一个线程来执行sell 方法
        synchronized (/*this*/ object) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                loop = false;
                return;
            }
            //休眠50 毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票"
                               + " 剩余票数=" + (--ticketNum));//1 - 0 - -1 - -2
        }
    }
    @Override
    public void run() {
        while (loop) {
            sell();//sell 方法是一共同步方法
        }
    }
}
//使用Thread 方式
// new SellTicket01().start()
// new SellTicket01().start();
class SellTicket01 extends Thread {
    private static int ticketNum = 100;//让多个线程共享ticketNum
    // public void m1() {
    // synchronized (this) {
    // System.out.println("hello");
    // }
    // }
    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                break;
            }
            //休眠50 毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票"
                               + " 剩余票数=" + (--ticketNum));
        }
    }
}
//实现接口方式
class SellTicket02 implements Runnable {
    private int ticketNum = 100;//让多个线程共享ticketNum
    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                break;
            }
            //休眠50 毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票"
                               + " 剩余票数=" + (--ticketNum));//1 - 0 - -1 - -2
        }
    }
}

注意事项

1)同步方法如果没有使用static修饰:默认锁对象为this

2)如果方法使用static修饰,默认锁对象:当前类.class

3)实现落地步骤:

  • 需要先分析上锁的代码
  • 选择同步代码块或同步方法
  • 要求多个线程的锁对象为同一个
线程的死锁

基本介绍:

多个线程都占用了对方的锁资源,但不肯相让,导致了死锁

image-20221031160639008

释放锁

image-20221031160901576

image-20221031160926143

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值