【线程状态-2】

1、线程礼让

(1)礼让线程,让当前正在执行的线程暂停,但不阻塞
(2)将线程从运行状态转为就绪状态
(3)让cpu重新调度,礼让不一定成功!看cpu心情
package state;
​
//测试礼让线程
//礼让不一定成功,看cpu心情
public class TestYield {
    public static void main(String[] args) {
        MyYield 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()+"线程停止执行");
    }
}
线程礼让成功

线程礼让失败

2、线程强制执行

package state;
​
//测试Join方法 想象为插队
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程VIP来了"+i);
        }
    }
​
    public static void main(String[] args) {
        TestJoin testJoin = new TestJoin();
        new Thread(testJoin).start();
​
        //主线程
        for (int i = 0; i < 1000; i++) {
            if (i==200){
                try {
                    new Thread(testJoin).join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("主线程"+i);
        }
    }
}

3、线程状态观测

package state;
​
//观察测试线程的状态
public class TestState {
    public static void main(String[] args) {
        //lambda表达式
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("///");
        });
​
        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);//New
        //观察启动后
        thread.start();//启动线程
        state = thread.getState();
        System.out.println(state);
​
        while (state!=Thread.State.TERMINATED){
            //只要线程不终止,就一直输出状态
            try {
                Thread.sleep(100);
                state = thread.getState();//更新线程状态
                System.out.println(state);//输出状态
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

  • 12
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值