java多线程的使用及易卡死的问题

最简单的用法

        Thread obd_thread = new Thread() {
            public void run() { // 重载的这个函数就是新建的线程了,里面可以跑 while大循环。
                while (true) {
                    // 延时1秒
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        obd_thread.start();

多线程易卡死的问题

    public void Environment_Init() throws InterruptedException {
        Thread obd_thread = new Thread() {
            public void run() { 
                String[] args = {""};
                main_dst(args);
            }
        };
        obd_thread.start();
        System.out.println("IsStartComplete--");
        while (IsStartComplete == false){Thread.sleep(100);}
        System.out.println("Environment_Init end.");
    }

比如,上面的这段代码,如果没有加 sleep() 延时函数,就会卡死,永远不会打印 "Environment_Init end.",这是多线程最容易错的地方,一个线程中没有sleep()函数,把CPU资源都占得满满的,别的线程就跑不起来了。

posted on 2020-11-16 16:03  lizhuohui  阅读(233)  评论(0编辑  收藏  举报

导航