进程与线程
- 进程
- 一个程序就是一个进程,经典定义是:一个执行中程序的实例。
- 线程
- 线程是进程执行的最小执行单元,一个进程可以包含多个线程。
什么是线程
1 |
|
线程的创建方式
1 |
|
线程的常见方法
- sleep
- causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
- yield
- basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.
- join
- The join() method of a Thread instance is used to join the start of a thread’s execution to end of other thread’s execution such that a thread does not start running until another thread ends. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing.
- join(n):It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).
参考:Java Concurrency – yield(), sleep() and join() methods
1 |
|
线程状态
- 新建状态——new Thread(),对象实例化后就是新建状态了。
- Runnable状态
- Ready就绪状态——thread.start(),任务被扔到CPU等待队列中,等待被运行。
- Running状态——被CPU调度器选中,开始执行,当顺利执行完后,进入Teminated结束状态,如果执行了yield(),当前线程会进入Ready就绪状态,等CPU调度器选中时,又进入Running状态。
- Teminated结束状态——顺利执行,任务进入Teminated结束状态后,不能重新start()。
- Bolcked阻塞 ——在执行同步代码块时没有获取锁资源,等获取锁了进入就绪状态。
- Waiting等待——在运行状态时调用o.wait()、t.join()、LockSupport.park()进入Waiting状态,调用o.notify()、o.notifyAll()、LockSupport.unpack()又回到Running状态。
- TimedWaiting等待——在运行状态时调用o.wait(n)、t.join(n)、Thread.sleep(n)进入TimedWaiting状态,与Waiting相似,只是按照时间等待,如果时间到了,或者线程结束则继续执行。
参考:Lifecycle and States of a Thread in Java
1 |
|