线程等待及守护线程问题

4 篇文章 0 订阅

线程等待:

  • (1) join
  • (2) 结合activeCount() + yield() 使用
  •     while (Thread.activeCount() > 1) { //用调试的方式运行
          Thread.yield();//将当前线程由运行态-->就绪态
        }
    

等待线程死亡

  • 当前线程:代码执行的时候,所在的线程
  • t 线程:线程引用对象
  • 当前线程进行阻塞(运行态–>阻塞态)等待(满足一定条件),t线程(不做任何处理,让t执行运行)
  • 条件:(哪个条件先执行完,先满足)
    a.传入时间(时间值+时间单位毫秒)
    b.线程引用对象执行完毕
public static void without() throws InterruptedException {
        // 打印顺序 main--->thread-0
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });
        t.start();
        t.join();
        System.out.println(Thread.currentThread().getName());
    }

    public static void withoutSleep() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });
        t.start();
        t.join(2000);
        System.out.println(Thread.currentThread().getName());
    }

    public static void withSleep() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("Thread baby");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        t.join(2000); // 调整参数 不传、1000、5000
        System.out.println("main");
    }

守护线程

public static void DaemonTest() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(99999999999L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "FirstTest");
        // 设置守护线程:后台进程
        // 非守护线程:工作线程
        t.setDaemon(true);
        t.start();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值