目录

  • 一、状态
  • 二、方法
    • 2.1 start()
    • 2.2 run()
    • 2.3 yield()
    • 2.4 join()
  • 三、状态与方法关系图

一、状态

线程共有6个状态。

状态 名称
new(新建状态) 用new创建的线程处于新建状态,此时他和其他的Java对象一样,仅仅在堆中分配了内存,没有调用start方法。
runable(就绪状态) 调用start方法,线程处于就绪状态
blocked(阻塞状态) 因为某些原因放弃CPU(缺少资源:IO、锁),暂时停止运行,进入阻塞状态
waiting(等待状态) 线程中的对象的调用wait()时,JVM就会将线程放入到等待池中
timed_waiting(睡眠状态) 在指定的等待时间内等待线程的状态
terminated(终止状态) 线程已经执行完毕

源码如下:

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;}
  1. 正常的线程只有四个状态:新建状态(NEW)、RUNNABLE(就绪状态)、终止状态(TERMINATED)。
  2. 非正常状态:阻塞状态(BLOCKED)、等待状态(WAITING)、睡眠状态(TIME WAITING)

二、方法

2.1 start()

启动操作系统的线程,进入就绪队列,等待CPU分配时间片,获取到时间片后执行线程的run方法。(start()只能执行一次

源码如下:

/*** Causes this thread to begin execution; the Java Virtual Machine* calls the <code>run</code> method of this thread.* <p>* The result is that two threads are running concurrently: the* current thread (which returns from the call to the* <code>start</code> method) and the other thread (which executes its* <code>run</code> method).* <p>* It is never legal to start a thread more than once.* In particular, a thread may not be restarted once it has completed* execution.** @exception  IllegalThreadStateException  if the thread was already*               started.* @see        #run()* @see        #stop()*/public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionality added* to this method in the future may have to also be added to the VM.** A zero status value corresponds to state "NEW".*/if (threadStatus != 0)throw new IllegalThreadStateException();/* Notify the group that this thread is about to be started* so that it can be added to the group's list of threads* and the group's unstarted count can be decremented. */group.add(this);boolean started = false;try {start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {/* do nothing. If start0 threw a Throwable thenit will be passed up the call stack */}}}

2.2 run()

业务逻辑的实现方法。

  1. 直接调用run方法不会启动线程
  2. 调用start方法以后,JVM会自动的运行run方法

源码如下:

/*** If this thread was constructed using a separate* <code>Runnable</code> run object, then that* <code>Runnable</code> object's <code>run</code> method is called;* otherwise, this method does nothing and returns.* <p>* Subclasses of <code>Thread</code> should override this method.** @see     #start()* @see     #stop()* @see     #Thread(ThreadGroup, Runnable, String)*/@Overridepublic void run() {if (target != null) {target.run();}}

2.3 yield()

将运行中的线程便会就绪状态,让出cpu的执行权,并通知操作系统从就绪线程中选出线程运行(可选择原来执行yield的线程)

注意:不释放资源

源码如下:

/*** A hint to the scheduler that the current thread is willing to yield* its current use of a processor. The scheduler is free to ignore this* hint.** <p> Yield is a heuristic attempt to improve relative progression* between threads that would otherwise over-utilise a CPU. Its use* should be combined with detailed profiling and benchmarking to* ensure that it actually has the desired effect.** <p> It is rarely appropriate to use this method. It may be useful* for debugging or testing purposes, where it may help to reproduce* bugs due to race conditions. It may also be useful when designing* concurrency control constructs such as the ones in the* {@link java.util.concurrent.locks} package.*/public static native void yield();

2.4 join()

当有新的线程加入时,主线程会进入等待(waiting)状态,一直到调用join()方法的线程执行结束为止。

当不调用join方法时,等到主线程执行完,才执行其他线程。

Runnable runnable = new RunnableDemo(){@Overridepublic void run() {System.out.println("执行中....");}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
System.out.println("执行完毕");

执行结果:

执行完毕
执行中....
执行中....

调用join方法时,先执行指定线程

Runnable runnable = new RunnableDemo(){@Overridepublic void run() {System.out.println("执行中....");}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();try{t1.join();t2.join();
}catch (Exception e){e.printStackTrace();
}
System.out.println("执行完毕");

执行结果:

执行中....
执行中....
执行完毕

三、状态与方法关系图

多线程(三)——了解线程相关推荐

  1. java多线程三之线程协作与通信实例

    多线程的难点主要就是多线程通信协作这一块了,前面笔记二中提到了常见的同步方法,这里主要是进行实例学习了,今天总结了一下3个实例: 1.银行存款与提款多线程实现,使用Lock锁和条件Condition. ...

  2. VC++中多线程学习(MFC多线程)三(线程同步包含:原子互锁、关键代码段、互斥器Mutex、Semaphores(信号量)、Event Objects(事件))

    目录 ​​​​​​​​​​​​ 线程同步的必要性: 2.解决同步问题的方法 2.1原子互锁家族函数 2.2Critical Sections(关键代码段.关键区域.临界区域) 2.3 互斥器Mutex ...

  3. Java讲课笔记33:多线程概述与线程创建

    文章目录 零.本讲学习目标 1.了解多线程的概念 2.掌握多线程创建的三种方式 3.熟悉创建多线程三种方式的主要区别 一.进程概述 (一)进程定义 (二)三维度看待进程模型 (三)进程说明 (四)进程 ...

  4. java 多线程输出_[Java多线程]ABC三个线程顺序输出的问题

    大概的问题是这样的: 有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C 要求, 同时启动三个线程, 按顺序输出ABC, 循环10次 这是一个多线程协同的问题, 本身多线程是没有执行 ...

  5. Java 多线程(三) 线程的生命周期及优先级

    Java 多线程(三) 线程的生命周期及优先级 线程的生命周期 线程的生命周期:一个线程从创建到消亡的过程. 如下图,表示线程生命周期中的各个状态: 线程的生命周期可以分为四个状态: 1.创建状态: ...

  6. java线程组 线程池_JAVA多线程(三)-----线程组、线程池和线程相关类

    一.线程组和未处理的异常 Thread类提供了如下几个构造器来设置新创建的线程属于哪个线程组: Thread(ThreadGroup group,Runnable target):以target的ru ...

  7. Java多线程:用三个线程控制循环输出10次ABC

    题目:有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C,要求, 同时启动三个线程, 按顺序输出ABC, 循环10次. 解题思路:要按顺序输出ABC, 循环10次,就要控制三个线程同 ...

  8. java多线程交替打印_使用Java实现三个线程交替打印0-74

    使用Java实现三个线程交替打印0-74 题目分析 三个线程交替打印,即3个线程是按顺序执行的.一个线程执行完之后,唤醒下一个线程,然后阻塞,等待被该线程的上一个线程唤醒.执行的顺序是一个环装的队列 ...

  9. 【Java面试高频-多线程】- 三个线程分别负责打印A,B和C,循环100次

    (2)面试真题-三个线程分别负责打印A,B和C,循环100次 a.ReentrantLock和Condition来完成这项工作 package com.lcz.thread; // 三个线程 // 匿 ...

  10. 【多线程】Java线程面试题 Top 50(转载)

    Java线程面试题 Top 50 原文链接:http://www.importnew.com/12773.html 本文由 ImportNew - 李 广 翻译自 javarevisited.欢迎加入 ...

最新文章

  1. shell脚本--02循环与条件
  2. Oracle根据符合条件的数据循环批量更新
  3. 模拟jQuery构造对象
  4. MYSQL [ERROR] InnoDB: Unable to lock ./ibdata1 error: 11
  5. jqgrid 列表条件查询的几步关键操作
  6. win32 粒子编辑器
  7. 如何使用百度云人脸识别服务(V3版接口python语言) (九)批量向人脸库中添加人脸
  8. arcMap安装教程
  9. 四、非平稳序列的确定性分析
  10. Windows 95, 98, Me 的界面对比(图集)(原文于2016-03-26发布于贴吧)
  11. 图论-拓扑排序(有向图)
  12. 宝宝去了幼儿园不爱说话怎么办?
  13. 用Ajax+js+jQuery实现无闪烁定时刷新页面 定时刷新
  14. 【老九学堂】【C语言进阶】内置函数补充
  15. 如何在阿里云开通云服务器
  16. 冒泡排序法定向冒泡排序法的Python实现
  17. 前端复习之HTML5
  18. 翻译(5): 技术债务墻:一种让技术债务可见并可协商的方法
  19. 放大、缩小chm文件字体的方法
  20. wireshark 802.11 WLAN无线报文分析常用技巧总结

热门文章

  1. app用mysql好处_用MYSQL对旅行app进行用户数据分析
  2. library netcdf 路径_中国科学院超级计算青岛分中心NETCDF4安装手册
  3. CITA v0.18 新增「基于 Rust 语言的国密算法库」新特性
  4. 名画22 周文矩《琉璃堂人物图》
  5. 2018年度中国电池行业百强企业名单发布
  6. 商品配送服务核销水票水站桶装水系统开发
  7. 汇总这一年半我所使用过的那些工具
  8. 世界杯“黑科技”进化史
  9. 简单的四位数字验证码
  10. php抓取运动步数,微信运动数据抓取(PHP)