Java学习day022-025(多线程-B站黑马版)

1.进程和线程

进程

进程:是正在运行的程序

  • 是系统进行资源分配和调用的独立单位
  • 每一个进程都有它自己的内存空间和系统资源

线程

线程:是进程中 的单个顺序控制流,是一条执行路径

  • 单线程:一个进程如果只有一条执行路径,则称为单线程程序
  • 多线程:一个进程如果有多条执行路径,则称为多线程程序

举例

  • 记事本程序
  • 扫雷程序

2.继承Thread类的方式实现多线程

方式1:继承Thread类

  • 定义一个类MyThread继承Thread类
  • 在MyThread类中重写run()方法
  • 创建MyThread类的对象
  • 启动线程

两个小问题:

  • 为什么要重写run()方法?
    • 因为run()是用来封装被线程执行的代码
  • run()方法和start()方法的区别?
    • run():封装线程执行的代码,直接调用,相当于普通方法的调用
    • start():启动线程;然后由JVM调用此线程的run()方法
package com.study_01;

public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(i);
        }
    }
}
package com.study_01;

public class MyThreadDemo {
    public static void main(String[] args) {
        MyThread my1 = new MyThread();
        MyThread my2 = new MyThread();

//        my1.run();
//        my2.run();

        // void start()导致此线程开始执行; Java虚拟机调用此线程的run方法。
        my1.start();
        my2.start();
    }
}

3.设置和获取线程名称

Thread类中设置和获取线程名称的方法

  • void setName(String name):将此线程的名称更改为等于参数name
  • String getName():返回此线程的名称
  • ·通过构造方法也可以设置线程名称

如何获取main()方法所在的线程名称?

  • public static Thread currentThread():返回对当前正在执行的线程对象的引用
package com.study_02;

public class MyThread extends Thread{
    public MyThread() {
    }

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(getName()+":"+i);
        }
    }
}

/*
    public Thread() {
        this(null, null, "Thread-" + nextThreadNum(), 0);
    }

    public Thread(ThreadGroup group, Runnable target) {
        this(group, target, "Thread-" + nextThreadNum(), 0);
    }

    private static int threadInitNumber; // 0
    private static synchronized int nextThreadNum() {
            return threadInitNumber++;
    }

 */
package com.study_02;

public class MyThreadDemo {
    public static void main(String[] args) {
        MyThread my1 = new MyThread();
        MyThread my2 = new MyThread();
//
//        // 线程更名
//        my1.setName("高铁");
//        my2.setName("飞机");

        // Thread(String name)
//        MyThread my1 = new MyThread("高铁");
//        MyThread my2 = new MyThread("飞机");
//
//        my1.start();
//        my2.start();

        // static Thread currentThread() 返回对当前正在执行的线程对象的引用。
        System.out.println(Thread.currentThread().getName());
    }
}

4.线程优先级

线程有两种调度模型

  • 分时调度模型:所有线程轮流使用CPU的使用权,平均分配每个线程占用CPU的时间片
  • 抢占式调度模型:优先让优先级高的线程使用CPU,如果线程的优先级相同,那么会随机选择一个,优先级高的线程获取的CPU时间片相对多一些

假如计算机只有一个CPU,那么CPU在某一个时刻只能执行一条指令,线程只有得到CPU时间片,也就是使用权,才可以执行指令。所以说多线程程序的执行是有随机性,因为谁抢到CPU的使用权是不一定的

Thread类中设置和获取线程优先级的方法

  • public final int getPriority():返回此线程的优先级
  • publicfinal void setPriority(int newPriority):更改此线程的优先级

线程默认优先级是5;线程优先级的范围是:1-10线程优先级高仅仅表示线程获取的CPU时间片的几率高,但是要在次数比较多,或者多次运行的时候才能看到你想要的效果

package com.study_03;

public class ThreadPriority extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(getName()+":"+i);
        }
    }
}
package com.study_03;

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        ThreadPriority tp1 = new ThreadPriority();
        ThreadPriority tp2 = new ThreadPriority();
        ThreadPriority tp3 = new ThreadPriority();

        tp1.setName("高铁");
        tp2.setName("飞机");
        tp3.setName("汽车");

        // 获取线程优先级
//        System.out.println(tp1.getPriority()); // 5
//        System.out.println(tp2.getPriority()); // 5
//        System.out.println(tp3.getPriority()); // 5

        // 更改线程优先级
//        tp1.setPriority(10000); // IllegalArgumentException

//        System.out.println(ThreadPriority.MAX_PRIORITY); // 10
//        System.out.println(ThreadPriority.MIN_PRIORITY); // 1
//        System.out.println(ThreadPriority.NORM_PRIORITY); // 5

        // 设置正确的优先级
        tp1.setPriority(5);
        tp2.setPriority(10);
        tp3.setPriority(1);


        tp1.start();
        tp2.start();
        tp3.start();


    }
}

5.线程控制

image-20210811074841275

6.线程的生命周期

image-20210811115911873

7.实现Runnable接口

方式2:实现Runnable接口

  • 定义一个类MyRunnable实现Runnable接口
  • 在MyRunnable类中重写run()方法
  • 创建MyRunnable类的对象
  • 创建Thread类的对象,把MyRunnable对象作为构造方法的参数
  • 启动线程

多线程的实现方案有两种

  • 继承Thread类
  • 实现Runnable接口

相比继承Thread类,实现Runnable接口的好处

  • 避免了Java单继承的局限性
  • 适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离,较好的体现了面向对象的设计思想
package com.study_05;

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}
package com.study_05;

public class MyRunnableDemo {
    public static void main(String[] args) {
        // 创建MyRunnable类的对象
        MyRunnable my = new MyRunnable();

        // 创建Thread类的对象,把MyRunnable对象作为构造方法的参数
        // Thread(Runnable target) 分配一个新的 Thread对象。
//        Thread t1 = new Thread(my);
//        Thread t2 = new Thread(my);

        // Thread(Runnable target, String name)
        Thread t1 = new Thread(my,"高铁");
        Thread t2 = new Thread(my,"飞机");

        //启动线程
        t1.start();
        t2.start();

    }
}

8.卖票

线程同步

image-20210811140811821

package com.study_06;

public class SellTicket implements Runnable {
    private int tickets = 100;

    @Override
    public void run() {
        while (true) {
                if (tickets > 0) {
                    // 通过Sleep()方法类模拟卖票时间
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                    tickets--;

            }
        }
    }
}
package com.study_06;

public class SellTicketDemo {
    public static void main(String[] args) {
        // 创建SellTicket类的对象
        SellTicket st = new SellTicket();

        // 创建三个Thread类的对象,把SellTicket对象作为构造方法的参数,并给出对应的窗口名称
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

9.卖票案例的思考

image-20210811161449676

10.同步代码块解决数据安全问题

为什么出现问题?(这也是我们判断多线程程序是否会有数据安全问题的标准准

  • 是否是多线程环境
  • 是否有共享数据
  • 是否有多条语句操作共享数据

如何解决多线程安全问题呢?

  • 基本思想:让程序没有安全问题的环境

怎么实现呢?

  • 把多条语句操作共享数据的代码给锁起来,让任意时刻只能有一个线程执行即可
  • Java提供了同步代码块的方式来解决k

同步代码块
锁多条语句操作共享数据,可以使用同步代码块实现

  • 格式:
synchronized(任意对象){
    多条语句操作共享数据的代码
}
  • synchronized(任意对象):就相当于给代码加锁了,任意对象就可以看成是一把锁

同步的好处和弊端

  • 好处:解决了多线程的数据安全问题
  • 弊端:当线程很多时,因为每个线程都会去判断同步上的锁,这是很耗费资源的,无形中会降低程序的运行效率
package com.study_08;

public class SellTicket implements Runnable {
    private int tickets = 100;
    private Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (obj) {
                if (tickets > 0) {
                    // 通过Sleep()方法类模拟卖票时间
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                    tickets--;
                }
            }
        }
    }
}
package com.study_08;

public class SellTicketDemo {
    public static void main(String[] args) {
        // 创建SellTicket类的对象
        SellTicket st = new SellTicket();

        // 创建三个Thread类的对象,把SellTicket对象作为构造方法的参数,并给出对应的窗口名称
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

11.同步方法解决数据安全问题

同步方法:就是把synchronized关键字加到方法上

  • 格式:
    • 修饰符synchronized返回值类型方法名(方法参数){ }

同步方法的锁对象是什么呢?

  • this

同步静态方法:就是把synchronized关键字加到静态方法上

  • 格式:
    • 修饰符static synchronized返回值类型方法名(方法参数){ }

同步静态方法的锁对象是什么呢?

  • 类名.class
package com.study_09;

public class SellTicket implements Runnable {
    //    private int tickets = 100;
    private static int tickets = 100;
    private Object obj = new Object();
    private int x = 0;

    @Override
    public void run() {
        while (true) {
            if (x % 2 == 0) {
//                synchronized (obj) {
//                synchronized (this) {
                synchronized (SellTicket.class) {
                    if (tickets > 0) {
                        // 通过Sleep()方法类模拟卖票时间
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                        tickets--;
                    }
                }
            } else {
//                synchronized (obj) {
//                    if (tickets > 0) {
//                        // 通过Sleep()方法类模拟卖票时间
//                        try {
//                            Thread.sleep(100);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
//                        tickets--;
//                    }
//                }
                SellTicket();
            }
            x++;
        }
    }

    //    public void SellTicket() {
//        synchronized (obj) {
//            if (tickets > 0) {
//                // 通过Sleep()方法类模拟卖票时间
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
//                tickets--;
//            }
//        }
//    }
    // 方法上加锁
//    public synchronized void SellTicket() {
//        if (tickets > 0) {
//            // 通过Sleep()方法类模拟卖票时间
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
//            tickets--;
//        }
//    }
    public static synchronized void SellTicket() {
        if (tickets > 0) {
            // 通过Sleep()方法类模拟卖票时间
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
            tickets--;
        }
    }
}
package com.study_09;

public class SellTicketDemo {
    public static void main(String[] args) {
        // 创建SellTicket类的对象
        SellTicket st = new SellTicket();

        // 创建三个Thread类的对象,把SellTicket对象作为构造方法的参数,并给出对应的窗口名称
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

12.线程安全的类

StringBuffer

  • 线程安全,可变的字符序列
  • 从版本JDK5开始,被StringBuilder 替代。通常应该使用StringBuilder类,因为它支持所有相同的操作,但它更快,因为它不执行同步

Vector

  • 从Java2平台v1.2开始,该类改进了List接口,使其成为Java Collections Framework的成员。与新的集合实现不同,Vector被同步。如果不需要线程安全的实现,建议使用ArrayList代替Vector

Hashtable

  • 该类实现了一个哈希表,它将键映射到值。任何非nul对象都可以用作键或者值
  • 从Java2平台v1.2开始,该类进行了改进,实现了Map接口,使其成为Java Collections Framework的成员。
    与新的集合实现不同,Hashtable被同步。如果不需要线程安全的实现,建议使用HashMap代替Hashtable
package com.study_10;

import java.util.*;

public class ThreadDemo {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        StringBuilder sb1 = new StringBuilder();

        Vector<String> v = new Vector<>();
        ArrayList<String> arrayList = new ArrayList<>();

        Hashtable<String ,String> ht = new Hashtable<>();
        HashMap<String,String> hm = new HashMap<>();

        // static <T> List<T> synchronizedList(List<T> list)
        // 返回由指定列表支持的同步(线程安全)列表
        List<String> list = Collections.synchronizedList(new ArrayList<String>());

    }
}

13.Lock锁

虽然我们可以理解同步代码块和同步方法的锁对象问题,但是我们并没有直接看到在哪里加上了锁,在哪里释放了锁,为了更清晰的表达

如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock

Lock实现提供比使用synchronized方法和语句可以获得更广泛的锁定操作

Lock中提供了获得锁和释放锁的方法

  • void lock():获得锁
  • void unlock():释放锁

Lock是接口不能直接实例化,这里采用它的实现类ReentrantLock来实例化

ReentrantLock的构造方法

  • Reentrantlock():创建一个ReentrantLock的实例
package com.study_11;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
    private int tickets = 100;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tickets > 0) {
                    // 通过Sleep()方法类模拟卖票时间
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                    tickets--;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
package com.study_11;

public class SellTicketDemo {
    public static void main(String[] args) {
        // 创建SellTicket类的对象
        SellTicket st = new SellTicket();

        // 创建三个Thread类的对象,把SellTicket对象作为构造方法的参数,并给出对应的窗口名称
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

14.生产者消费者模式

生产者消费者模式是一个十分经典的多线程协作的模式,弄懂生产者消费者问题能够让我们对多线程编程的理解更加深刻所谓生产者消费

者问题,实际上主要是包含了两类线程:

  • 一类是生产者线程用于生产数据
  • 一类是消费者线程用于消费数据

为了解耦生产者和消费者的关系,通常会采用共享的数据区域,就像是一个仓库

  • 生产者生产数据之后直接放置在共享数据区中,并不需要关心消费者的行为
  • 消费者只需要从共享数据区中去获取数据,并不需要关心生产者的行为

image-20210811192705029

为了体现生产和消费过程中的等待和唤醒,Java就提供了几个方法供我们使用,这几个方法在Objec类中Object类的等待和唤醒方法:

image-20210811192747113

15.生产者消费者案例

image-20210811210446647

package com.study_12;

public class Box {
    // 定义牛奶数量
    private int milk;
    // 定义一个成员变量,表示奶箱的状态
    private boolean state = false;

    // 提供存储牛奶的操作
    public synchronized void put(int milk) {
        // 如果有牛奶,等待消费
        if (state) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 如果没有,就生产牛奶
        this.milk = milk;
        System.out.println("送奶工将第"+this.milk+"瓶奶放入奶箱");

        // 生产完毕,修改奶箱状态
        state = true;

        // 唤醒
        notifyAll();

    }

    public synchronized void get() {
        // 如果没有,等待生产
        if(!state) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 如果有就消费
        System.out.println("用户拿到第"+this.milk+"瓶奶");
        state = false;
        // 唤醒
        notifyAll();
    }

}
package com.study_12;

public class Customer implements Runnable{
    private Box b;
    public Customer(Box b) {
        this.b = b;
    }

    @Override
    public void run() {
        while (true){
            b.get();
        }

    }
}
package com.study_12;

public class Producer implements Runnable{
    private  Box b;
    public Producer(Box b) {
        this.b = b;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            b.put(i);
        }
    }
}
package com.study_12;

public class BoxDemo {
    public static void main(String[] args) {
        // 创建奶箱队形,这是共享数据区域
        Box b = new Box();

        // 创建生产者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶的操作
        Producer p = new Producer(b);
        // 创建消费者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶的操作
        Customer c = new Customer(b);

        // 创建两个线程对象
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);

        // 启动线程
        t1.start();
        t2.start();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值