java线程的isAlive()方法不能正常工作? [英] isAlive() method of java thread is not working properly?

查看:132
本文介绍了java线程的isAlive()方法不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个 isAlive() java线程方法的示例。但我发现 isAlive()方法返回 false ,即使线程已经启动。有人可以告诉我,我做错了什么?这是代码片段。

I was trying a example of isAlive() method of java threading. But i found that isAlive() method is returning false even if thread has been already started. Can someone please tell me what am i doing wrong? Here is the code snippet.

package app;

public class ThreadAliveDemo {

    public static void main(String[] args) {

        Thread myThread;

        myThread = new Thread()
        {
            public void run()
            {
                            Thread.sleep(3000);
                System.out.println("My Thread.");
            }
        };

        myThread.setName("My Thread");
        myThread.start();

        if(!myThread.isAlive())
        {
            myThread.setName("My Thread");
            myThread.start();
        }

    }

}


推荐答案

如果我的记忆很好,java在线程切换之间有很长的时间,所以isAlive可能会失败,因为线程还没有活着。尝试在thread.start()和thread.isAlive()

If my memory serves me well java has quite long periods between thread switching so it is possible that the isAlive fails because the thread is not yet alive. Try to add some waiting time between thread.start() and thread.isAlive()

这篇关于java线程的isAlive()方法不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆