Java线程状态变换过程代码解析

网友投稿 257 2022-12-05


Java线程状态变换过程代码解析

线程状态

NEW:刚创建未启动的线程

RUNNABLE:正在执行状态

BLOCKED:处于阻塞状态的线程

WAITING:正在等待另一个线程执行特定动作的线程

TIMED_WAITING:等待另一个线程执行时间到达指定时间

TERMINATED:线程退出执行

public class TestState {

public static void main(String[] args) {

Thread thread = new Thread(()->{

for (int i = 0; i < 5; i++) {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("/////");

});PzbvlFSabD

//观察线程状态

Thread.State state = thread.getState();

System.out.println(state); //New状态

thread.start();

state = thread.getState();

System.out.println(state);//Run状态

while (state!=Thread.State.TERMINATED){

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

state = thread.getState();//更新线程状态

System.out.println(state);//输出状态

}

}

}

线程礼让

当前正在执行的线程暂停,但是不会阻塞

当前线程失去处理机,编程就绪状态

礼让是否成功取决于CPU,如果礼让成功,则等待下一次调度

public class TestYield {

public static void main(String[] args) {

Myhttp://Yield myYield = new MyYield();

new Thread(myYield,"a").start();

new Thread(myYield,"b").start();

}

}

class MyYield implements Runnable{

@Override

public void run() {

System.out.println(Thread.currentThread().getName()+"线程开始执行");

Thread.yield();

System.out.println(Thread.currentThread().getName()+"线程停止执行");

}

}

执行结果:

线程强制执行到结束

使用join()方法

使用join()方法的线程会强制执行直到结束,不会让出处理机

public class TestJoin implements Runnable{

@Override

public void run() {

for (int i = 0; i < 1000; i++) {

System.out.println("强制执行线程来了"+i);

}

}

public static void main(String[] args) throws Exception{

TestJoin testJoin = new TestJoin();

Thread thread = new Thread(testJoin);

thread.start();

for (int i = 0; i < 500; i++) {

if(i==200){

thread.join();

}

System.out.println("主线程"+i);

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Springboot接口项目如何使用AOP记录日志
下一篇:使用IDEA启动项目遇见ClassNotFoundException的解决方案
相关文章

 发表评论

暂时没有评论,来抢沙发吧~