多线程学习Day02

今天多搞一点

两阶段终止模式

概念

两阶段终止模式(Two-Phase Termination Pattern)是一种设计模式,通常用于多线程编程中确保系统在终止前能平稳、有序地关闭其资源和线程。这种模式特别适合用于需要优雅关闭操作的应用程序,如多线程的服务器或者需要清理资源的复杂系统。

基本工作原理
  1. 第一阶段 - 触发终止

    • 在这一阶段,系统接收到终止信号(例如用户输入、系统命令或其他形式的触发条件)。这个信号会通知程序开始准备关闭。
    • 程序设置一个终止标志,表明系统即将关闭。
  2. 第二阶段 - 执行终止

    • 一旦终止标志被设置,系统将执行具体的终止操作。这可能包括关闭资源(如文件、网络连接)、停止服务、通知所有工作线程结束等。
    • 这个阶段的关键是确保所有关键资源都被正确释放,所有线程都能有序地终止。

在一个线程t1中优雅的终止t2线程(给t2一个料理后事的机会)

例如使用stop()方法杀死线程这显然是不靠谱的,System.exit()方法这种直接把整个程序都停止了,显然都不行。示例代码在此。(打断线程有isInterrupted()方法和interrupted()方法,前者不会清除打断标记,后者会清除打断标记)

@Slf4j(topic="c.Test3")
public class Test3 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt=new TwoPhaseTermination();
        tpt.start();

        Thread.sleep(5000);
        tpt.stop();
    }
}
@Slf4j(topic="c.TwoPhaseTermination")
class TwoPhaseTermination{
    private Thread monitor;//监控线程
    //启动监控线程
    public void start(){
        monitor=new Thread(()->{
            while (true){
                Thread current= Thread.currentThread();
                if(current.isInterrupted()){
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重新设置打断标记,没有这句话的话无法正确退出循环,因为sleep出现异常后会清除打断标记
                    current.interrupt();
                }
            }
        });
        monitor.start();
    }
    //停止监控线程
    public void stop(){
        monitor.interrupt();
    }
}

打断park线程,这个感觉不用说太多,需要注意的是如果打断标记为真,park就会失效,比如可以用interrupted()方法打断后自动清除打断标记。

不太好的方法

stop()、suspend()、resume(),这些容易破坏同步代码块,造成线程死锁。

主线程和守护线程

默认情况下,Java 进程需要等待所有线程都运行结束,才会结束。有一种特殊的线程叫做守护线程,只要其它非守护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束。

最常见的应用是垃圾回收器,Tomcat 中的 Acceptor 和 Poller 线程都是守护线程,所以 Tomcat 接收到 shutdown 命令后,不会等待它们处理完当前请求

线程的状态-五种状态(操作系统层面描述)

勾起了我尘封的回忆

【初始状态】仅是在语言层面创建了线程对象,还未与操作系统线程关联
【可运行状态】(就绪状态)指该线程已经被创建(与操作系统线程关联),可以由 CPU 调度执行
【运行状态】指获取了 CPU 时间片运行中的状态,当 CPU 时间片用完,会从【运行状态】转换至【可运行状态】,会导致线程的上下文切换
【阻塞状态】
如果调用了阻塞 API,如 BIO 读写文件,这时该线程实际不会用到 CPU,会导致线程上下文切换,进入【阻塞状态】等 BIO 操作完毕,会由操作系统唤醒阻塞的线程,转换至【可运行状态】
与【可运行状态】的区别是,对【阻塞状态】的线程来说只要它们一直不唤醒,调度器就一直不会考虑调度它们
【终止状态】表示线程已经执行完毕,生命周期已经结束,不会再转换为其它状态

线程的状态-六种状态(Java Api层面描述)

NEW 线程刚被创建,但是还没有调用 start() 方法
RUNNABLE 当调用了 start() 方法之后,注意,Java API 层面的 RUNNABLE 状态涵盖了操作系统层面的【可运行状态】、【运行状态】和【阻塞状态(由于 BIO 导致的线程阻塞,在 Java 里无法区分,仍然认为是可运行)
BLOCKED , WAITING , TIMED_WAITING 都是 Java API 层面对【阻塞状态】的细分
TERMINATED 当线程代码运行结束

一个练习

给一个多线程解决方案

                                   

两个线程拿下,这个解法还是有一定缺陷的,确实离真正的实际还有一定差距


@Slf4j(topic ="c.Test4")
public class Test4 {
    public static void main(String[] args) {
        //线程1用来洗水壶和烧开水
        Thread t1=new Thread(()->{
            log.debug("{}开始洗水壶",Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug("{}开始烧开水",Thread.currentThread().getName());
            try {
                Thread.sleep(15000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"t1");
        Thread t2=new Thread(()->{
           log.debug("{}开始洗茶壶",Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug("{}开始洗茶杯",Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug("{}开始拿茶叶",Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
             try {
                t1.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug("{}开始泡茶喽",Thread.currentThread().getName());
        },"t2");
        t1.start();
        t2.start();
    }
}

结果

14:19:22 [t2] c.Test4 - t2开始洗茶壶
14:19:22 [t1] c.Test4 - t1开始洗水壶
14:19:23 [t1] c.Test4 - t1开始烧开水
14:19:23 [t2] c.Test4 - t2开始洗茶杯
14:19:25 [t2] c.Test4 - t2开始拿茶叶
14:19:38 [t2] c.Test4 - t2开始泡茶喽

共享模型之管程

共享带来的问题

这里我觉得细说的必要不大,这个代码的结果千奇百怪,字节码指令交错加上上下文切换

@Slf4j(topic = "c.Test5")
public class Test5 {
    static int counter = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                counter++;
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                counter--;
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}",counter);
    }
}
临界区 Critical Section
 

一个程序运行多个线程本身是没有问题的,问题出在多个线程访问共享资源,多个线程读共享资源其实也没有问题,在多个线程对共享资源读写操作时发生指令交错,就会出现问题,一段代码块内如果存在对共享资源的多线程读写操作,称这段代码块为临界区

竞态条件 Race Condition

多个线程在临界区内执行,由于代码的执行序列不同而导致结果无法预测,称之为发生了竞态条件

synchronized解决方案

它采用互斥的方式让同一时刻至多只有一个线程能持有【对象锁】,其它线程再想获取这个【对象锁】时就会阻塞住。这样就能保证拥有锁的线程可以安全的执行临界区内的代码,不用担心线程上下文切换

语法

synchronized(对象) // 线程1, 线程2(blocked)
{
临界区
}

用它解决刚才的问题

@Slf4j(topic = "c.Test5")
public class Test5 {
    static int counter = 0;
    static Object lock=new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock){
                    counter++;
                }

            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock){
                    counter--;
                }
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}",counter);
    }
}

原理

synchronized 实际是用对象锁保证了临界区内代码的原子性,临界区内的代码对外是不可分割的,不会被线程切换所打断。

面向对象改进

@Slf4j(topic = "c.Test5")
public class Test5 {

    public static void main(String[] args) throws InterruptedException {
        Room room=new Room();
        Thread t1 = new Thread(() -> {

            for (int i = 0; i < 5000; i++) {
                room.increment();

            }
        }, "t1");
        Thread t2 = new Thread(() -> {

            for (int i = 0; i < 5000; i++) {
                room.decrement();
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}",room.getCounter());
    }
}
class Room{
    private int counter=0;
    public void increment(){
        synchronized (this){
            counter++;
        }
    }
    public void decrement(){
        synchronized (this){
            counter--;
        }
    }
    public int getCounter(){
        synchronized (this){
            return counter;
        }
    }
}

线程八锁

考察锁住的是哪个对象

情况1:显然可以锁住,锁的是同一个对象,结果是12或者21

@Slf4j(topic = "c.Number")
class Number{
public synchronized void a() {
log.debug("1");
}
public synchronized void b() {
log.debug("2");
}
}
public static void main(String[] args) {
Number n1 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n1.b(); }).start();
}

情况2:1s后12或者2 1s后1

@Slf4j(topic = "c.Number")
class Number{
public synchronized void a() {
sleep(1);
log.debug("1");
}
public synchronized void b() {
log.debug("2");
}
}
public static void main(String[] args) {
Number n1 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n1.b(); }).start();
}

情况3:3肯定在1之前(3 1s 1 2)(2 3 1s 1)(3 2 1s 1)

class Number{
public synchronized void a() {
sleep(1);
log.debug("1");
}
public synchronized void b() {
log.debug("2");
}
public void c() {
log.debug("3");
}
}
public static void main(String[] args) {
Number n1 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n1.b(); }).start();
new Thread(()->{ n1.c(); }).start();
}

情况4:2 1s 1 这里是两个对象,等于没有锁

@Slf4j(topic = "c.Number")
class Number{
public synchronized void a() {
sleep(1);
log.debug("1");
}
public synchronized void b() {
log.debug("2");
}
}
public static void main(String[] args) {
Number n1 = new Number();
Number n2 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n2.b(); }).start();
}

情况5:2 1s 1这里a锁住的是类对象,b锁住的是示例对象,其实是不同的对象

@Slf4j(topic = "c.Number")
class Number{
public static synchronized void a() {
sleep(1);
log.debug("1");
}
public synchronized void b() {
log.debug("2");
}}
public static void main(String[] args) {
Number n1 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n1.b(); }).start();
}

情况6:1s 1 2 或者2 1s 1 这里锁住的都是类对象

@Slf4j(topic = "c.Number")
class Number{
public static synchronized void a() {
sleep(1);
log.debug("1");
}
public static synchronized void b() {
log.debug("2");
}
}
public static void main(String[] args) {
Number n1 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n1.b(); }).start();
}

情况7:2 1s 1 还是不同对象

@Slf4j(topic = "c.Number")
class Number{
public static synchronized void a() {
sleep(1);
log.debug("1");
}
public synchronized void b() {
log.debug("2");
}
}
public static void main(String[] args) {
Number n1 = new Number();
Number n2 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n2.b(); }).start();
}

情况8:1s 1 2或者2 1s 1 无需多言

class Number{
public static synchronized void a() {
sleep(1);
log.debug("1");
}
public static synchronized void b() {
log.debug("2");
}
}
public static void main(String[] args) {
Number n1 = new Number();
Number n2 = new Number();
new Thread(()->{ n1.a(); }).start();
new Thread(()->{ n2.b(); }).start();
}

  • 16
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值