多线程--常用方法

前面我们学习到了多线程的一些概念,现在跟着我一起学习多线程的常用的方法吧

1.获得线程的各种属性

1.1获得线程对象

Thread.currentThread()

1.2获得当前执行的方法名

Thread.currentThread().getStackTrace()[1].getMethodName()

1.3获得线程对象名

 线程对象.getName()

通过类 + 方法 + 线程名的写法能构成线程的日志,在工作中更好的找到问题所在 

2.得到线程的各种状态 

 

 

3.后台线程

线程名.setDaemor(true);

设置成后台线程之后,当执行到main就会结束

 public static void main(String[] args) {
        Thread thread = new Thread(()->{
            while(true){
                System.out.println("thread....");
            }
        });
        thread.setDaemon(true);
        thread.start();
        System.out.println("线程是否存活" + thread.isAlive());
        System.out.println("main.....");
    }

前台线程可以阻止进程的退出,后台线程不可以阻止进程的推出 

4.线程是否存活

public static void main(String[] args) throws InterruptedException {
        Thread th = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                System.out.println("hello thread.....");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("启动前线程是否存活" + th.isAlive());
        th.start();
        System.out.println("启动后线程是否存活" + th.isAlive());
        th.join();
        Thread.sleep(1000);
        System.out.println("线程结束后是否存活" + th.isAlive());
    }

 

5.线程中断

 

方法一:设置全局变量,通过更改全局变量来改变线程内循环的变量来中断

static boolean iQuit = false;
    public static void main(String[] args) throws InterruptedException {

        Thread th = new Thread(()->{
            while(!iQuit){
                System.out.println("hello ,thread...");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程退出。。。");
        });
        th.start();
        Thread.sleep(5000);
        iQuit = true;
    }

 

 

方法二:通过编译器内置的函数,循环内写

!Thread.currentThread().isInterrupted()

然后在结尾可以对变量进行更改

线程名.interrupt(); 
public static void main(String[] args) throws InterruptedException {
        Thread th = new Thread(()->{
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("hello, thread...");
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    System.out.println("休眠被中断");
//                    break;
//                }
            }
            System.out.println("线程以中断");
        });
        th.start();
        Thread.sleep(1000);
        th.interrupt();
    }

当中断过程中如果有sleep的话,会报错然后将sleep中断,然后继续进行线程,这时就需要在异常处手动退出即可 

未手动退出时

手动退出时

6.线程等待-join()方法 

等待线程走完后才能进行下一步 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值