本文共 4009 字,大约阅读时间需要 13 分钟。
其实很多时候我们在调用线程的时候,是需要进行这样几个步骤的
1:线程的创建new Thread() 2:线程的执行() 3:线程的wait()或者sleep() 4:线程执行完毕之后的dead 当然上面可能是一种相对比较笼统的总结,其实在线程的整个生命周期包括了一下几点以及线程的阻塞状态
在Thread源码中,其是通过枚举Enum类型来进行生命周期分类的:
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: *
A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called Object.wait() * on an object is waiting for another thread to call * Object.notify() or Object.notifyAll() on * that object. A thread that has called Thread.join() * 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: *
可以看到其系统分为
NEW, RUNABLE, BLOCKED, WAITING, TIME_WAITING, TERMINATED当线程处于新建状态的时候,该线程仅仅是一个空的对象,系统并未对其分配任何资源Thread th = new Thread();这个时候我们可以通过其相关的set方法:如: setName() setPriority(); setDaemon();等方法对我们的线程进行分类。注意:在new Thread的时候线程的ID默认会自增的,也就是在前一个线程的ID基础之上做了加1操作,从代码 /* For autonumbering anonymous threads. */ private static int threadInitNumber; private static synchronized int nextThreadNum() { return threadInitNumber++;} public Thread() { init(null, null, "Thread-" + nextThreadNum(), 0);}中可以看出,Thread系统默认的名字是固定格式的,其他几个构造函数其实也是类似的。
就绪状态其实也就是对应的Runable状态,这个时候启动start方法启动一个线程系统会为其分配出来cpu资源以外的所有资源。进入就绪状态注意: 当使用yeild()方法后,这个线程就会被剥夺掉cpu资源。从而再次进入就绪状态
线程的运行状态也叫做Runing状态,java系统通过调度会去选中一个正在就绪状态的线程,从而使其占有cpu的资源并且转化为运行状态,这个时候才是真正的去调用线程的run方法;
阻塞状态blocked状态,这个状态也是线程中相对比较复杂的一种状态,因为导致这种阻塞状态的因素相对也比较多当一个线程在运行的过程中,由于某种原因而不能继续去执行的时候,这个时候也就进入了阻塞状态原因: 1:执行sleep的时候,线程会被置入阻塞blocked pool中 2:当多个线程师徒进入某一个同步区域的时候,没能进入的线程会被置入(锁定集)lock pool,直到获得该同步锁 3:当线程执行某个对象的wait方法的时候,会被放置入等待集(wait pool)中,直到该对象调用notify()方法
线程处于了dead状态,就是线程已经执行完毕后。会将资源释放。
线程死亡的几种原因: 1:线程已经执行完毕了,会进入死亡状态 2:线程执行了stop或者interrupt方法,就会以一种异常的方式进入死亡状态其实在这里需要注意的是终止线程的几种方法: 1:使用退出方式,使线程正常退出,当run方法运行完毕后终止 2:调用stop方法 3:调用interrupt方法 而调用stop或者interrupt方法的时候,都是会往外抛出异常的。这属于程序执行异常
这是 官方在线javaapi,有兴趣的可以去看一下,其实在开发中,我们使用的也仅仅是常用方法。有些方法也并不是太经常使用
其实相对来说,这些理论只是都比较简单,但是作为一个程序员,基础决定你的高度吧。因为之前遇到过很多问题其实都是因为线程的使用不规范。或者多个线程同时,导致其时序发生很多变化导致的。所以 在这里才浅析下线程
转载地址:http://rwbsn.baihongyu.com/