Java 多线程(2)---- 线程的控制

前言

在上一篇文章中我们简单的认识了一下线程。包括线程的优先级、如何创建一个线程(通过继承 Thread 类或者通过新建 Runnable 对象并作为参数传入 Thread 的构造方法中)、线程的声明周期状态(新建状态、运行状态(就绪状态、正在运行状态)、等待状态、阻塞状态、结束状态),最后我们看了一下守护线程的概念和其特点。如果你对线程的一些概念还不熟悉,建议先从第一篇文章看起:Java 多线程(1)— 初识线程,当然,大神请无视这句话。
这篇文章我们来看一下 Java 多线程中对线程的控制。

线程控制

其实对一个线程的控制简单来说无非 3 种:开启线程、暂停线程、停止线程:
开启线程我们上篇文章已经使用过了,就是一个当线程对象调用start() 方法后(start() 方法只能被调用一次),这个线程就进入就绪状态了,正在等待线程调度器调度该线程,而一旦线程调度器调度了该线程之后,该线程便可获得 CPU 资源,进入正在运行状态。

如果我们需要暂停一个正在执行的线程时,我们可以通过调用该线程对象的 sleep(long millis) 方法来让该线程休眠指定的秒数,调用这个方法之后线程将会让出 CPU 进入休眠,休眠完成之后的线程并不会直接获得 CPU 资源,而是会进入就绪状态,等待着线程调度器的调度来获取 CPU 资源。

对于停止线程,可能有些小伙伴会通过调用线程对象的 stop() 来停止线程,但这个方法已经不被官方推荐使用了:
这里写图片描述
我们可以看看源码中关于这个方法的注释:

Because it is inherently unsafe. 
Stopping a thread causes it to unlock all the monitors that it has locked.
(The monitors are unlocked as the ThreadDeath exception propagates up the stack.) 
If any of the objects previously protected by these monitors were in an inconsistent state, 
other threads may now view these objects in an inconsistent state. 
Such objects are said to be damaged. When threads operate on damaged objects, 
arbitrary behavior can result. 
This behavior may be subtle and difficult to detect, or it may be pronounced. 
Unlike other unchecked exceptions, ThreadDeath kills threads silently;
thus, the user has no warning that his program may be corrupted.
The corruption can manifest itself at any time after the actual damage occurs, 
even hours or days in the future.

这个官方文档写的有点抽象啊。。。
大致意思是:Thread.stop 方法是不安全的ÿ

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值