Java多线程

1. 概念

在维基百科中解释道

多线程(英语:multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能。具有这种能力的系统包括对称多处理机、多核心处理器以及芯片级多处理(Chip-level multithreading)或同时多线程(Simultaneous multithreading)处理器。

2. 作用

  1. 上面定义中看出,在硬件的支持下,在同一时间运行多线程,能够提升处理器的性能。现在大部分电脑都是多核cpu,充分利用多核的资源。
  2. 防止线程阻塞,如果是单线程,如果一个线程停止,则会影响后面的进程的运行,导致线程阻塞。

3. 使用

3.1 线程周期

  1. 新建状态,当程序使用new关键字创建了一个线程之后,该线程就处于新建状态,此时仅由JVM为其分配内存,并初始化其成员变量的值

  2. 就绪状态,当线程对象调用了start()方法之后,该线程处于就绪状态。Java虚拟机会为其创建方法调用栈和程序计数器,等待调度运行

  3. 运行状态,如果处于就绪状态的线程获得了CPU,开始执行run()方法的线程执行体,则该线程处于运行状态

  4. 阻塞状态,当处于运行状态的线程失去所占用资源之后,便进入阻塞状态

  5. 在线程的生命周期当中,线程的各种状态的转换过程

在这里插入图片描述

3.3 线程创建

/**
 * 线程创建第一种方式
 * 1. 继承Thread
 */
public class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("线程的第一次种创建方式");
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.run();
    }
}


/**
 * 线程创建第二种方式
 * 1. 实现Runnable接口
 */
class MyThread2 implements Runnable {

    @Override
    public void run() {
        System.out.println("线程创建的第二种方式");
    }

    public static void main(String[] args) {
        MyThread2 thread = new MyThread2();
        thread.run();
    }
}


/**
 * 线程创建第三种方式
 * 1. 实现Callable接口
 * 2. 创建futureTask实例,用Callable作为参数
 *
 * @param <T>
 */
class MyCallable<T> implements Callable<T> {

    @Override
    public T call() throws Exception {
        System.out.println("线程创建的第三种方式");
        return null;
    }

    public static void main(String[] args) {

        FutureTask futureTask =new FutureTask<>(new MyCallable<>());
        Thread thread = new Thread(futureTask);
        thread.run();
    }
}

3.4 关闭线程

stop()
这里stop() jdk中是不推荐使用的,官方的解释

@deprecated This method is inherently unsafe. Stopping a thread with
* Thread.stop causes it to unlock all of the monitors that it
* has locked (as a natural consequence of the unchecked
* ThreadDeath exception propagating up the stack). If
* any of the objects previously protected by these monitors were in
* an inconsistent state, the damaged objects become visible to
* other threads, potentially resulting in arbitrary behavior. Many
* uses of stop should be replaced by code that simply
* modifies some variable to indicate that the target thread should
* stop running. The target thread should check this variable
* regularly, and return from its run method in an orderly fashion
* if the variable indicates that it is to stop running. If the
* target thread waits for long periods (on a condition variable,
* for example), the interrupt method should be used to
* interrupt the wait.

废弃的原因:这个方法是不安全的,stop 会解除所有的监视的锁
代替:应该用线程中断来处理interrupt



 Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("run...");
            }

        });
        thread.start();
        try {
            Thread.sleep(5000);
            thread.stop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

3.5 线程中断

  1. 通过interrupt()方法优雅的终止进程
Thread thread = new Thread(() -> {
            while (true) {
            	//判断当前进程是否被中断
                if (Thread.currentThread().interrupted()) {
                    break;
                }
                try {
                   //此处加上会出现异常
                   // Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //设置中断状态 ,因为抛出异常会取消中断状态
                    Thread.currentThread().interrupt();
                }
                System.out.println("run...");
            }

        });
        thread.start();
        try {
            Thread.sleep(5000);
             //中断进程
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

在测试的过程遇到一个异常,进程还在继续运行,判断进程是否中断失败,这个异常是使用sleep()方法抛出的,原因是线程在睡眠的时候,有人在中断,抛出的异常,给出反馈做一些处理。
所以在异常catch中必须重新设置中断

run...
run...
run...
run...
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at KillThread.lambda$main$0(KillThread.java:10)
	at java.lang.Thread.run(Thread.java:745)
run...
run...
run...
run...
run...

  1. suspend方法挂起线程,需要通过resume解除,继续执行程序
  • suspend 不会释放锁
  • 如果锁发生在resume之前,会出现死锁

3.6 yeid()

what: Yield告诉当前正在执行的线程把运行机会交给线程池中拥有相同优先级的线程。
why : 能使一个线程从运行状态转到可运行状态,而不是等待或阻塞状态。

3.7 join()

what: 使得一个线程在另一个线程结束后再执行

3.8 守护线程

what:JVM实例中尚存任何一个非守护线程没有结束,守护线程就全部工作;只有当最后一个非守护线程结束是,守护线程随着JVM一同结束工作
why: 为其他线程提供便利服务,守护线程最典型的应用就是GC(垃圾回收器),他就是一个很称职的守护者。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱折腾的Albert

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值