线程状态
- 创建状态
- 就绪状态
- 阻塞状态
- 运行状态
- 死亡状态
线程方法
停止线程
线程休眠 sleep()
- sleep(毫秒数)指定当前线程停止的实践
- sleep()存在异常InteruptedException
- sleep()实践到达后线程进入就绪状态
- sleep()可以模拟网络延时,倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
线程礼让 yield()
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让CPU重新调度,礼让不一定成功,看CPU心情
线程强制执行 join()
- Join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞
- 可以想象成插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5000; i++) {
System.out.println("VIP"+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 1000; i++) {
if (i == 20){
thread.join();
}
System.out.println("普通"+i);
}
}
}
线程状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("///////////");
});
Thread.State state = thread.getState();
System.out.println(state);
thread.start();
state = thread.getState();
System.out.println(state);
while (state != Thread.State.TERMINATED){
Thread.sleep(500);
state = thread.getState();
System.out.println(state);
}
}
}
线程优先级
java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程;线程调度器按照优先级决定该调度哪个线程来执行
线程的优先级用数字来表示,范围从1~10
Thread.MIN_PRIORITY = 1
Thread.MAX_PRIORITY= 10
Thread.NORM_PRIORITY = 5
使用getPriority()和setPriority()来获取或改变优先级
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。(性能倒置)
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-----"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread = new Thread(myPriority);
thread.setPriority(10);
thread.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-----"+Thread.currentThread().getPriority());
}
}
守护线程setDeamon()
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕(main)
虚拟机不用等待守护线程执行完毕(GC)
如后台记录操作日志,监控内存,垃圾回收