本文共 3049 字,大约阅读时间需要 10 分钟。
new 尚未启动的线程处于此状态
Runnable 在java虚拟机中执行的线程处于此状态
Blocked 被阻塞等待监视器锁定的线程处于此状态。
Waiting 正在等待另一个线程执行特定动作的线程处于此状态。
Timed Waiting 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
Terminated 已退出的线程处于此状态。
代码案例
/** * 线程的状态 */public class TestThreadStatus{ public static void main(String[] args) throws InterruptedException { //我们用lamda表达式来启动一个线程 Thread th = new Thread(()->{ for (int i = 0; i <5 ; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(""); }); Thread.State state = th.getState(); System.out.println("创建时线程的状态+"+state);//线程的状态 th.start();//启动线程 state = th.getState(); System.out.println("启动时线程的状态+"+state); //只要线程不终止就输入线程状态 while (state != Thread.State.TERMINATED){ Thread.sleep(100); state = th.getState(); System.out.println("new+"+state); } }}
java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
线程的优先级用数字表示,范围从1~10。
使用以下方式改变或获取优先级
代码案例:
/** * 线程优先级,不一定成功 */public class TestThreadPriority { public static void main(String[] args) { MyPriority myPriority = new MyPriority(); Thread t1 = new Thread(myPriority); Thread t2 = new Thread(myPriority); Thread t3 = new Thread(myPriority); Thread t4 = new Thread(myPriority); Thread t5 = new Thread(myPriority); Thread t6 = new Thread(myPriority); //先设置线程优先级 t1.setPriority(1); t1.start(); t2.setPriority(3); t2.start(); t3.setPriority(6); t3.start(); t4.setPriority(Thread.MAX_PRIORITY);// 优先级=10 t4.start(); t5.setPriority(Thread.MIN_PRIORITY);// 优先级=1 t6.setPriority(9); t6.start(); System.out.println("main"); }}class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"---线程被执行了!---"+Thread.currentThread().getPriority()); }}
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕
代码案例
public class TestDaemon { public static void main(String[] args) { God god = new God(); You you=new You(); Thread thread = new Thread(god); thread.setDaemon(true);//默认为flase 为用户线程, true为守护线程 thread.start(); new Thread(you).start(); }}class God implements Runnable{ @Override public void run() { while (true){ System.out.println("上帝守护着你-------"); } }}class You implements Runnable{ @Override public void run() { for (int i = 0; i <36500 ; i++) { System.out.println("开心着活着每一天------"); } System.out.println("----goodbye!Beautiful World!!!------"); }}
Java多线程扩展: