架构师成长之旅第一篇
程序员文章站
2022-07-14 15:17:37
...
架构师成长之旅第一篇
日常积累
线程的状态:
状态 | 解释 |
---|---|
NEW | 新建状态,尚未启动状态 |
RUNNABLE | 就绪状态 正在运行或者是排队等待CPU给它分配资源 |
BLOCKED | 阻塞等待锁的状态,等待监视器锁,比如等待执行synchronized代码块或者使用synchronized标记的方法 |
WAITING | 等待状态,正在等待另一个线程执行某个特定的动作,比如调用了Object.wait()方法,等待另一个线程调用Object.notify()或者notifyAll()方法 |
TIMED_WAITING | 计时等待状态 比如调用了Object.wait(long timeout)和Thread.join(long timeout)等这些方法时,它才会进入此状态 |
TERMINATED | 终止状态,执行完毕 |
线程状态源代码如下:
public enum State{
NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED,
}
Runnable的run方法和Thread的start方法区别
- run方法只是Runnable接口的一个普通方法可以执行多次,需要调用类重写此方法,执行此方法就是执行业务
- start方法是Thread类的线程安全的启动方法,只能执行一次
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 */
}
}
}
线程的优先级
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;