一、状态
线程共有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;
}
- 正常的线程只有四个状态:新建状态(NEW)、RUNNABLE(就绪状态)、终止状态(TERMINATED)。
- 非正常状态:阻塞状态(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 then
it will be passed up the call stack */
}
}
}
2.2 run()
业务逻辑的实现方法。
- 直接调用run方法不会启动线程
- 调用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)
*/
@Override
public 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(){
@Override
public 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(){
@Override
public 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("执行完毕");
执行结果:
执行中....
执行中....
执行完毕