线程定义 线程,有时被称为轻量级进程(lightweight process,lwp),是程序执行流的最小单元。一个标准的线程由线程id,当前指令指针(pc),寄存器集合和堆栈组成。如果没有明确的协同机制,线程将彼此独立执行。每一个程序都至少有一个线程,若程序只有一个线程,那就是程序本身。
线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源(共享进程的内存地址空间),因此这些线程都能访问相同的变量并在同一个堆上分配对象,这就需要实现一种比在进程间共享数据粒度更细的数据共享机制。如果没有这种同步机制,在多线程的情况下会出现无法预料的后果。
一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。由于线程之间的相互制约,致使线程在运行中呈现出间断性。线程也有就绪、阻塞和运行三种基本状态。就绪状态是指线程具备运行的所有条件,逻辑上可以运行,在等待处理机;运行状态是指线程占有处理机正在运行;阻塞状态是指线程在等待一个事件(如某个信号量),逻辑上不可执行。
线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派cpu的基本单位指运行中的程序的调度单位。在单个程序中同时运行多个线程完成不同的工作,称为多线程。
java中的线程 一个java程序的入口是main方法,通过调用main方法开始执行,然后按照代码逻辑执行,看似没有其他线程参与,其实java程序天生就是多线程程序,执行一个main方法其实就是一个名为mian的线程和其他线程分别执行,参考代码如下:
代码(参考java并发编程艺术)package com.sunld;import java.lang.management.managementfactory;import java.lang.management.threadinfo;
import java.lang.management.threadmxbean;/**
* @title: testmainthread.java
* @package com.sunld
* <p>description:</p>
* @author sunld
* @version v1.0.0
* <p>createdate:2017年9月28日 下午3:54:19</p>
*/public class testmainthread {
public static void main(string[] args) { // 获取java线程管理mxbean
threadmxbean threadmxbean = managementfactory.getthreadmxbean(); // 不需要获取同步的monitor和synchronizer信息,仅获取线程和线程堆栈信息
threadinfo[] threadinfos = threadmxbean.dumpallthreads(false, false); // 遍历线程信息,仅打印线程id和线程名称信息
for (threadinfo threadinfo : threadinfos) {
system.out.println("[" + threadinfo.getthreadid() + "] " +
threadinfo.getthreadname());
}
}
}
返回结果[5] attach listener//附加监听
[4] signal dispatcher//分发处理发送给jvm信号的线程
[3] finalizer//调用对象finalize方法的线程
[2] reference handler清除reference的线程
[1] mainmain线程,用户程序入口
线程状态源码定义 /**
* a thread state. a thread can be in one of the following states:
* <ul>
* <li>{@link #new}<br>
* a thread that has not yet started is in this state.
* </li>
* <li>{@link #runnable}<br>
* a thread executing in the java virtual machine is in this state.
* </li>
* <li>{@link #blocked}<br>
* a thread that is blocked waiting for a monitor lock
* is in this state.
* </li>
* <li>{@link #waiting}<br>
* a thread that is waiting indefinitely for another thread to
* perform a particular action is in this state.
* </li>
* <li>{@link #timed_waiting}<br>
* a thread that is waiting for another thread to perform an action
* for up to a specified waiting time is in this state.
* </li>
* <li>{@link #terminated}<br>
* a thread that has exited is in this state.
* </li>
* </ul>
*
* <p>
* 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.
*
* @since 1.5
* @see #getstate
*/
public enum state {
/**
* thread state for a thread which has not yet started.
*/
new,
/**
* thread state for a runnable thread. a thread in the runnable
* state is executing in the java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
runnable,
/**
* thread state for a thread blocked waiting for a monitor lock.
* a thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link object#wait() object.wait}.
*/
blocked,
/**
* thread state for a waiting thread.
* a thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link object#wait() object.wait} with no timeout</li>
* <li>{@link #join() thread.join} with no timeout</li>
* <li>{@link locksupport#park() locksupport.park}</li>
* </ul>
*
* <p>a thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* for example, a thread that has called <tt>object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>object.notify()</tt> or <tt>object.notifyall()</tt> on
* that object. a thread that has called <tt>thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
waiting,
/**
* thread state for a waiting thread with a specified waiting time.
* a thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep thread.sleep}</li>
* <li>{@link object#wait(long) object.wait} with timeout</li>
* <li>{@link #join(long) thread.join} with timeout</li>
* <li>{@link locksupport#parknanos locksupport.parknanos}</li>
* <li>{@link locksupport#parkuntil locksupport.parkuntil}</li>
* </ul>
*/
timed_waiting,
/**
* thread state for a terminated thread.
* the thread has completed execution.
*/
terminated;
}
状态转换图
状态说明
java多线程的就绪、运行和死亡状态就绪状态转换为运行状态:当此线程得到处理器资源;
运行状态转换为就绪状态:当此线程主动调用yield()方法或在运行过程中失去处理器资源。
运行状态转换为死亡状态:当此线程线程执行体执行完毕或发生了异常。
此处需要特别注意的是:当调用线程的yield()方法时,线程从运行状态转换为就绪状态,但接下来cpu调度就绪状态中的哪个线程具有一定的随机性,因此,可能会出现a线程调用了yield()方法后,接下来cpu仍然调度了a线程的情况。
由于实际的业务需要,常常会遇到需要在特定时机终止某一线程的运行,使其进入到死亡状态。目前最通用的做法是设置一boolean型的变量,当条件满足时,使线程执行体快速执行完毕(不在执行run方法)在后续的文章中会介绍如何安全的终止一个线程。。
状态分析–jvisualvm代码-参考(java并发编程艺术)package com.sunld;
import java.util.concurrent.timeunit;/**
* @title: testthreadstate.java
* @package com.sunld
* <p>description:</p>
* @author sunld
* @version v1.0.0
* <p>createdate:2017年9月28日 下午5:14:27</p>
*/public class testthreadstate {
public static void main(string[] args) {
new thread(new timewaiting (), "timewaitingthread").start();
new thread(new waiting(), "waitingthread").start(); // 使用两个blocked线程,一个获取锁成功,另一个被阻塞
new thread(new blocked(), "blockedthread-1").start();
new thread(new blocked(), "blockedthread-2").start();
} //该线程不断地进行睡眠
static class timewaiting implements runnable{
@override
public void run() {
sleeputils.second(100);
}
} //该线程在waiting.class实例上等待
static class waiting implements runnable{
@override
public void run() {
while (true) {
synchronized (waiting.class) {
try {
waiting.class.wait();
}catch(interruptedexception e) {
e.printstacktrace();
}
}
}
}
} //该线程在blocked.class实例上加锁后,不会释放该锁
static class blocked implements runnable {
@override public void run() {
synchronized (blocked.class) {
while (true) {
sleeputils.second(100);
}
}
}
}
}class sleeputils{
public static final void second(long seconds) {
try {
timeunit.seconds.sleep(seconds);
}catch(interruptedexception e) {
e.printstacktrace();
}
}
}
dump结果2017-09-28 17:26:47full thread dump java hotspot(tm) 64-bit server vm (25.112-b15 mixed mode):
//blockedthread-2线程获取到了blocked.class的锁"blockedthread-2" #13 prio=5 os_prio=0 tid=0x000000001f268000 nid=0x3754 waiting on condition [0x000000002009f000]
java.lang.thread.state: timed_waiting (sleeping)
//blockedthread-1线程阻塞在获取blocked.class示例的锁上"blockedthread-1" #12 prio=5 os_prio=0 tid=0x000000001f266800 nid=0x89c waiting for monitor entry [0x000000001ff9f000]
java.lang.thread.state: blocked (on object monitor)
//waitingthread线程在waiting实例上等待"waitingthread" #11 prio=5 os_prio=0 tid=0x000000001f260800 nid=0x4d08 in object.wait() [0x000000001fe9f000]
java.lang.thread.state: waiting (on object monitor)
//timewaitingthread线程处于超时等待"timewaitingthread" #10 prio=5 os_prio=0 tid=0x000000001f25f000 nid=0x42ac waiting on condition [0x000000001fd9e000]
java.lang.thread.state: timed_waiting (sleeping)
以上就是java并发之线程的使用以及基本概念的详细内容。