线程基础---基础方法

线程基础---基础方法,第1张

线程启动

在Thread类中注释标明有两种方式创建新的执行线程:

  1. 一种是声明一个类是Thread的子类。这个子类应该重写类Thread的run方法。然后可以分配和启动子类的实例
  2. 创建线程的另一种方法是声明一个实现Runnable接口的类。这个类然后实现run方法。然后可以分配类的实例,在创建Thread时作为参数传递,并启动

两种方式对比:

  1. 从java语法方面来看,java没有多继承,如果使用继承Thread的方式,就不能再继承其他类,限制了代码的可扩展性
  2. 从效率方面来看,如果通过实现Runnable接口的方式,可以作为一个任务当做参数传入到线程中,这时的线程可以使用线程池。而通过继承的方式,每次创建和销毁线程相对来讲会消耗资源,效率并不高
中止线程 错误方式

stop():已弃用,停止方式会使业务逻辑不完整

正确方式

interrupt()

将中断位标记设置位true

isInterrupted()

返回该线程的中断标记位

interrupted()

返回重置当前线程的中断标记位

interrupt():推荐使用,简单来讲就是向线程发送一个中止信号,但该线程是否中止,什么时候中止,取决于目标线程的应答

isInterrupted():返回该线程的中断标记位,可以搭配interrupt()组合使用

使用interrupt()中止一个正在运行的线程:

public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) {
                // 搭配isInterrupted()正常中止线程
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("thread 正常中止");
                    break;
                }
            }
        });
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

中断正在休眠的线程:

private static final Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            synchronized (lock) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("flag");
            }
        });
        thread.start();
        // 此时中断TIME_WATING状态的线程,会抛出InterruptedException
        // wait(), wait(long),wait(long, int)  join(), join(long), join(long, int), sleep(long),  sleep(long, int), cleared and it will receive an InterruptedException.
        // interrupt方法注释明确标注:如果在使用上述方法期间被打断,会重置标记位并抛出一个异常
        thread.interrupt();
    }
**********运行结果****************
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.nuc.demo.thread.CarThread.lambda$main$0(CarThread.java:33)
	at java.lang.Thread.run(Thread.java:748)
false

备注:凡是会抛出InterruptedException信息的方法,一般都会在其抛出异常之前将当前线程的中断标志位重置为false

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/731595.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存