java并发编程学习(2)

线程的生命周期和start方法

线程的生命周期如下

线程生命周期流程

在new Thread()后,线程并没有真正启动,只有在调用start方法后,才会成为一个线程。但是线程并不会立即执行,它处于可执行状态,即runnable状态,等待cpu的调度。当被分配到cpu执行权,就到了running状态。在running的过程中,如果sleep或者等待锁,就会处于blocked状态。被block后,不能立即进入running状态,只能回到runnable状态。同时处于running中的线程,也会进入runnable状态。这几种状态都能进入终结状态。

start
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Throws:
IllegalThreadStateException - if the thread was already started.
See Also:
run(), stop()

文档中对start方法的描述,调用start后会导致产生一个新的线程,一个线程不能调用两次start().

总结一下:

  1. Java程序的main方法是一个线程,在被JVM启动时调用,线程名称是main
  2. 实现一个线程,必须创建Thread实例,重新run方法,并调用start方法
  3. 在JVM启动后,实际上有多个线程,但至少有一个非守护线程
  4. 当调用一个线程的start方法,此时至少有2个线程,一个是调用start方法的线程,另一个是执行run方法的线程
  5. 线程的生命周期分为new,runnable,running,blocked,terminated几种状态
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值