Java 复习 —— 守护线程以及线程监测工具


1、守护线程

Java线程机制分为两种 ,用户线程(User Thread)和守护线程(Daemon Thread)。

用户线程:运行在前台,执行具体的任务。例如:程序的主线程,连接网络的子线程。

守护线程:运行在后台,为其他线程提供服务的。例如:垃圾回收器线程

线程异同:一旦所有的用户线程都运行结束,守护线程会随JVM一起退出,其实这就是守护线程应该的生命周期,因为他是服务于其用户线程的线程,当用户线程一旦执行完毕,守护线程的职责就结束了,理该退出!但是用户线程是不会在主线程结束的时候而退出的。

线程应用:用户线程一般执行在特定的任务上,守护线程一般使用在 数据库连接池中的监测线程,JVM启动后监测线程等。



2、API

Thread t1 = new Thread(sample);
t1.setDaemon(true);
t1.start();

1)thread.setDaemon(true)必须在thread.start()之前设置,否则会跑出一个IllegalThreadStateException异常。换句话说,你不能把正在运行的常规线程设置为守护线程。

2) 在Daemon线程中产生的新线程也是Daemon的。

3)注意读写操作或者计算逻辑是不能使用守护线程的。因为在Daemon Thread还没来的及操作时,虚拟机可能已经退出。


3、线程监测工具

1)使用jstack生成线程快照,在JDK的bin目录下

2)jstat.exe 命令行工具的使用,在JDK的bin目录下

3)jvisualvm.exe 界面化工具的使用,SUN公司提供,同样在JDK的bin目录下

JDK 安装的bin目录下有这几个文件

104306_sxdP_1989321.png

通过DOS窗口如下执行jstack -l pid ,查看线程的运行状态,这里就要注意线程的生命周期的六大状态

这里PID可以通过任务管理器的——查看——选择列——勾选PID即可查看

104328_mBnu_1989321.png

A thread state. A thread can be in one of the following states:

  • NEW
    A thread that has not yet started is in this state.

  • RUNNABLE
    A thread executing in the Java virtual machine is in this state.

  • BLOCKED
    A thread that is blocked waiting for a monitor lock is in this state.

  • WAITING
    A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

  • TIMED_WAITING
    A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

  • TERMINATED
    A thread that has exited is in this state.

A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.


使用jvisualvm.exe 查看线程状态,只要启动界面程序,该程序就会自动去搜索java程序,并且监控程序中线程使用情况

104359_pggu_1989321.png



转载于:https://my.oschina.net/heweipo/blog/505228

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值