java sleep、yield、join

public class T03_Sleep_Yield_Join {
    public static void main(String[] args) {
//        testSleep();
        testYield();
//        testJoin();
    }

    /**
    Sleep 意思就是睡眠,当前线程暂停一段时间让给别的线程去运行,Sleep是怎么复活的?
        由你的睡眠时间决定,等睡眠到规定时间自动复活
     */
    static void testSleep(){
        new Thread(()->{
            for(int i = 0;i<10;i++){
                System.out.println("A"+i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * Yield 就是当前线程正在执行的时候停止下来进入等待队列,回到等待队列里在系统的调度算法里,
     * 还有可能把你刚放回去的线程拿出来继续执行,当然,更大的可能性是把原来等待的那些拿出来一个执行,
     * 所以yield的意思是我让出cpu,后面你们能不能抢到那我不管
     */
    static void testYield(){
        new Thread(()->{
            for(int i = 0;i<10;i++){
                System.out.println("A"+i);
                if(i%2 == 0){
                    Thread.yield();
                }
            }
        }).start();

        new Thread(()->{
            for(int i = 0;i<10;i++){
                System.out.println("B"+i);
                if(i%2 == 0){
                    Thread.yield();
                }
            }
        }).start();
    }

    /**
     * join 意思就是在自己当前线程加入你调用Join的线程(),本线程等待.等调用的线程运行完了,自己再去执行,
     * t1和t2两个线程,在t1的某个点上调用t2.join(),他会跑到t2去运行,t1等待t2运行完毕继续t2运行(自己join自己没有意义)
     */
    static void testJoin(){
        Thread t1 = new Thread(()->{
            for(int i = 0;i<10;i++){
                System.out.println(Thread.currentThread()+" "+i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(()->{
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for(int i = 0;i<10;i++){
                System.out.println(Thread.currentThread()+" "+i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值