线程状态
状态相关方法
方法 | 说明 |
---|---|
setPriority(int) | 更改线程优先级 |
static void sleep(long) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt | 中断线程,不建议使用 |
boolean isAlive() | 测试线程是否处于活动状态 |
线程停止
不建议使用JDK提供的stop()、destory()方法(已废弃)。推荐使用一个标志位(boolean flag)。改变flag,让线程自己停下来。
举例:主线程循环900次时,改变标志位,让开辟的线程停止
public class TestThreadStop implements Runnable{
//定义标志位
private Boolean flag = true;
//停止的方法,即改变标志位
public void stop(){
flag = false;
}
public static void main(String[] args) {
TestThreadStop testThreadStop = new TestThreadStop();
new Thread(testThreadStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("主线程 "+i);
if(i == 900) {
testThreadStop.stop();
System.out.println("主线程将要停止了");
}
}
}
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run------thread " + i++);
}
}
}
线程休眠sleep
- sleep(int) 在指定的毫秒数内让当前正在执行的线程休眠
- sleep存在异常interruptedException
- sleep时间达到后线程重新进入就绪状态
- 可以模拟网络延时、倒计时
- 每个对象都有一把锁,sleep时这个线程不会释放锁(以后章节讲)
举例:每过一秒钟输出系统时间(即线程休眠一秒后输出)
public class TestThreadSleep{
public static void main(String[] args) throws InterruptedException {
//时间戳,System.currentTimeMillis()
//获取当前时间,很复杂 Sun Aug 15 16:46:24 CST 2021
Date date = new Date(System.currentTimeMillis());
while(true){
//主线程休眠
Thread.sleep(1000);
//定义简单的时间格式,并输出
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
//更新时间
date = new Date(System.currentTimeMillis());
}
}
}
线程礼让yield
让当前正在执行的线程暂停,但不阻塞,直接进入就绪状态,重新与其他进程争夺CPU资源。
因此礼让不一定成功,得看CPU。
Thread.yield();
强制执行Join
Join合并线程,等待此线程执行完成后,再执行其他线程,其他线程阻塞。可以理解为插队
public class TestThreadJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 500; i++) {
System.out.println("Yip来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestThreadJoin threadJoin = new TestThreadJoin();
Thread thread = new Thread(threadJoin);
thread.start();
for (int i = 0; i < 1000; i++) {
if(i == 800){
thread.join();
}
System.out.println("主线程"+i);
}
}
}
观测线程状态
NEW:尚未启动的线程处于此状态。
RUNNABLE:在Java虚拟机中执行的线程处于此状态。
BLOCKED:被阻塞等待监视器锁的线程处于这种状态。
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 Object.wait
.
WAITING:无限期等待另一个线程执行特定操作的线程处于此状态。
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods: Object.wait
with no timeout、Thread.join
with no timeout、LockSupport.park
TIMED_WAITING: 一个线程正在等待另一个线程执行操作达指定的等待时间时处于此状态。
A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:Thread.sleep
、Object.wait
with timeout、Thread.join
with timeout、LockSupport.parkNanos
、LockSupport.parkUntil
TERMINATED:已退出的线程处于此状态。
thread.getState()获取此线程状态。下面测试在不同时期的线程状态
public class TestThreadState{
public static void main(String[] args) {
//线程内执行五次,睡觉
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//启动前状态
Thread.State state = thread.getState();
System.out.println(state);
//启动后状态
thread.start();
state = thread.getState();
System.out.println(state);
//开辟的线程没有死的话,就一直循环
while(state != Thread.State.TERMINATED) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//此时开辟的线程正在sleep
state = thread.getState();
System.out.println(state);
}
}
}
线程优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该先调度哪个线程来执行。但具体调用谁还是看CPU,是概率问题,不是百分百的
优先级用数字表示,范围1~10。Thread.MIN_PRIORITY=1、Thread.MAX_PRIORITY=10、Thread.NORM_PRIORITY=5。默认为5
改变优先级getPriority()
,优先级的设置建议在start之前。获取优先级setPriority(int)