20240427-线程基础-线程常用方法(二)

线程基础-线程常用方法(二)

1.守护线程

  • 线程在默认情况下都是非守护线程
  • JVM会在程序没有非守护线程的情况下结束
package com.ysf.day0427;

public class Tst01DaemonThread {

    public static void main(String[] args) {
        Thread t = new Thread(()->{
            for (int i = 0;i<10;i++){
                System.out.println(i);
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // 执行完t.start()后,主线程结束,但因为t线程是非守护线程,所以程序仍会运行
        t.start();
    }
}
package com.ysf.day0427;

public class Tst01DaemonThread {

    public static void main(String[] args) {
        Thread t = new Thread(()->{
            for (int i = 0;i<10;i++){
                System.out.println(i);
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.setDaemon(true);
        t.start();
        // 执行完t.start()后,主线程结束,但因为t线程是守护线程,所以程序结束
    }
}

2.线程的等待和唤醒

锁的等待池:在锁的等待池中的线程是没有资格竞争锁的
锁池:在锁池中的线程才有资格竞争锁

2.1 wait()方法

  • 作用
    让获取到锁的线程去到锁的等待池,并且释放锁资源

2.2 notify()或notifyAll()

  • 作用
    将锁的等待池中的线程唤醒,添加到锁池,重新竞争锁资源
  • 区别
    notify()方法随机唤醒一个线程
    notifyAll()方法唤醒所有线程

2.3调用方

  • 由谁来调用wait()方法和notify()方法呢?
    来调用
  • 为什么要由锁来调用呢?
    因为大家都是来竞争同一把锁的,wait()的目的是让获取到锁的线程不再竞争锁,并且释放锁,notify()的目的是让大家再重新回来竞争锁,
    前提都是要获取到锁或者获取过锁才行,那就只能由锁来调用。
  • 那谁来调用锁呢?
    所以还得有一个控制线程来调用锁,而且这个线程必须要获取到锁才能去调用锁,所以得在synchronized()方法中去调用
package com.ysf.day0427;

public class Tst02WaitNotify {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            sync();
        },"wn-1");
        Thread t2 = new Thread(()->{sync();},"wn-2");
        t1.start();
        t2.start();
        // 控制主线程的睡眠,确保t1和t2能在主线程之前获取到锁
        Thread.sleep(3600L);
        synchronized (Tst02WaitNotify.class){
            System.out.println("主线程获取到锁,开始唤醒锁等待池中的所有线程...");
            Tst02WaitNotify.class.notifyAll();
        }
    }

    public static synchronized void sync(){
        for (int i = 0;i<10;i++){
            String name = Thread.currentThread().getName();
            System.out.println(name +"==>"+i);
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (("wn-1".equals(name) && i==5) || ("wn-2".equals(name) && i==4)){
                try {
                    Tst02WaitNotify.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值