博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Thread类当中sleep, join ,yield方法
阅读量:4149 次
发布时间:2019-05-25

本文共 2090 字,大约阅读时间需要 6 分钟。

    简述:线程类当中提供了一些辅助方法,以便我们在使用线程时,来完成不同的场景下的操作

    sleep()方法

    sleep 方法有个重载方法,sleep(long), sleep(long,int )

    sleep方法是让出CPU执行权,但是并不会释放到当前线程所拥有的锁对象,这个是和wait方法不同的地方。

    Thread.yield方法

        yield方法没有参数,是让出当前线程,让其他就绪的线程去执行,也不会保证当前线程立刻会停止,

        注:调用yield方法只是把当前线程放入到就绪队列中去,而不是阻塞队列,如果其他线程没有就绪状态,那么当前线程将会继续进行,yield可以让低于优先级的线程执行。

        yield并不能保证线程的交替进行

    Thread.join 方法

     join方法是父线程等待子线程执行结束,通俗点来讲就是,如果在线程A当中,调用线程B.join方法,那么线程A必须在等待线程B执行结束之后,才会接着往下执行。

public class JoinTest {    public static void main(String[] args) throws Exception{        Thread previous = Thread.currentThread();        for(int i = 0; i < 10; i++) {            Thread thread = new Thread(new Domino(previous),String.valueOf(i));            thread.start();            previous = thread;        }        TimeUnit.SECONDS.sleep(5);        System.out.println(Thread.currentThread().getName()+" terminate.");    }    static class Domino implements Runnable{        private Thread thread;        public Domino(Thread thread) {            this.thread = thread;        }        @Override        public void run() {            try{                thread.join();            }catch (Exception e){            }            System.out.println(Thread.currentThread().getName()+" terminate");        }    }}

其执行结果是

main terminate.0 terminate1 terminate2 terminate3 terminate4 terminate5 terminate6 terminate7 terminate8 terminate9 terminate

Thread类当中对join的方法实现,其实是调用了wait方法

public final synchronized void join(long millis)    throws InterruptedException {        long base = System.currentTimeMillis();        long now = 0;        if (millis < 0) {            throw new IllegalArgumentException("timeout value is negative");        }        if (millis == 0) {            while (isAlive()) {                wait(0);            }        } else {            while (isAlive()) {                long delay = millis - now;                if (delay <= 0) {                    break;                }                wait(delay);                now = System.currentTimeMillis() - base;            }        }    }

在调用完wait方法之后,什么时候调用notify方法

这个是在jvm当中进行调用处理,当调用join的线程执行完之后,会自动唤醒主线程执行下去。

转载地址:http://oovti.baihongyu.com/

你可能感兴趣的文章
Android中启动其他Activity并返回结果
查看>>
2009年33所高校被暂停或被限制招生
查看>>
GlassFish 部署及应用入门
查看>>
X-code7 beta error: warning: Is a directory
查看>>
Error: An App ID with identifier "*****" is not avaliable. Please enter a different string.
查看>>
3.5 YOLO9000: Better,Faster,Stronger(YOLO9000:更好,更快,更强)
查看>>
iOS菜鸟学习--如何避免两个按钮同时响应
查看>>
iOS菜鸟学习—— NSSortDescriptor的使用
查看>>
CORBA links
查看>>
如何使用BBC英语学习频道
查看>>
初识xsd
查看>>
java 设计模式-职责型模式
查看>>
构造型模式
查看>>
svn out of date 无法更新到最新版本
查看>>
java杂记
查看>>
RunTime.getRuntime().exec()
查看>>
Oracle 分组排序函数
查看>>
删除weblogic 域
查看>>
VMware Workstation 14中文破解版下载(附密钥)(笔记)
查看>>
日志框架学习
查看>>