卷帘门怎么做网站,网页设计与网站开发素材,出入沈阳最新通知今天,固原市住房和城乡建设局网站介绍
Java 线程在运⾏的⽣命周期中的指定时刻只可能处于下⾯ 6 种不同状态的其中⼀个状态
状态名称说明NEW初始状态,线程被构建,但是还没有调用start()方法RUNNABLE运行状态,Java线程将操作系统中的就绪和运行两种状态统称为运行中BLOCKED阻塞状态,表示线程阻塞于…介绍
Java 线程在运⾏的⽣命周期中的指定时刻只可能处于下⾯ 6 种不同状态的其中⼀个状态
状态名称说明NEW初始状态,线程被构建,但是还没有调用start()方法RUNNABLE运行状态,Java线程将操作系统中的就绪和运行两种状态统称为运行中BLOCKED阻塞状态,表示线程阻塞于锁WAITING等待状态,表示线程进入等待状态进入该状态表示当前线程需要其他线程通知(notify或者notifyAll)TIME_WAITING超时等待状态,可以指定等待时间自己返回TERMINATED终止状态表示当前线程已经执行完毕
查看Thread类中定义了一个State枚举类型
public enum State {/*** Thread state for a thread which has not yet started.*/NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED;}各种状态的demo
NEW public void test1() { //NEWThread t1 new Thread(() - {System.out.println(Thread1~~~~);});System.out.println(t1.getState());}这个时候线程刚刚创建还没有调用start()方法,所以状态为NEW
TERMINATED Testpublic void test2() throws InterruptedException { //TERMINATEDThread t1 new Thread(() - {System.out.println(线程开始执行);System.out.println(线程结束执行);});t1.start();Thread.sleep(3000);System.out.println(t1.getState());}线程执行结束后查看状态为TERMINATED,加sleep是为了保证在getState的时候线程已经执行结束
RUNNABLE Testpublic void test3() { //RUNNABLEThread t1 new Thread(() - {});t1.start();System.out.println(t1.getState());}调用了start()方法后线程处于RUNNABLE状态。
注意:线程创建之后它将处于 NEW新建 状态调⽤ start() ⽅法后开始运⾏线程这时候处于READY可运⾏ 状态。可运⾏状态的线程获得了 cpu 时间⽚timeslice后就处于RUNNING运⾏ 状态。操作系统隐藏 Java 虚拟机JVM中的 READY 和 RUNNING 状态它只能看到 RUNNABLE 状态。所以Java系统把这两个状态统称为RUNNABLE状态。
BLOCKED
这边我们模拟一个我们模拟找桌子用餐的场景 学生1和学生2同时争夺一个座位用餐学生一先抢到座位学生2就处于阻塞的状态只能等待学生1用餐结束
public class Test1 {public static void main(String[] args) throws InterruptedException {System.out.println(Thread.currentThread().getName());Table table new Table();Thread student1 new Thread(() - {table.use();}, s1);Thread student2 new Thread(() - {table.use();}, s2);student1.start();Thread.sleep(1000);student2.start();Thread.sleep(500);System.out.println(student2.getState());}
}
class Table { public synchronized void use() {System.out.println(Thread.currentThread().getName() -使用桌子);try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() 就餐结束);}
}
WAITING
这边我们模拟学生1在得到座位后发现自己忘记点餐了所以只能让出座位这个资源。进入wait状态
public class Test2 {public static void main(String[] args) throws Exception {System.out.println(Thread.currentThread().getName());Table1 table new Table1();Thread student1 new Thread(() - {try {table.use();} catch (Exception e) {e.printStackTrace();}}, s1);student1.start();Thread.sleep(100);System.out.println(student1.getState());Thread.currentThread().getState();}
}class Table1 { public synchronized void use() throws Exception {System.out.println(Thread.currentThread().getName() -使用桌子);//忘记点餐了System.out.println(忘记点餐了);wait(100);Thread.sleep(2000);System.out.println(Thread.currentThread().getName() 就餐结束);}
}
TIME_WAITING
这个在WAITING的基础上加了一个自动返回的时间就算没有其他线程通知它过了一定的时间它也会自动返回。