java - 如何自动调用方法来停止线程?

标签 java multithreading oop race-condition event-listener

我正在实现一个小项目,其中雌性胎生动物可以怀孕(一个实现 Runnable 的类)。

这是我的妊娠类(class):

private final class Gestation implements Runnable //inner class of Viviparous
{                                                
        private boolean isWorking;
        private Viviparous[] babies;
        private final int time_end;
        private int time_left;
        private Enclosure e;

        public Gestation(Viviparous[] b, Enclosure e)
        {
            if(Viviparous.this instanceof Lion) 
                this.time_end = Lion.TIME_GESTATION;
            else if(Viviparous.this instanceof Gazelle) 
                this.time_end = Gazelle.TIME_GESTATION;
            else if(Viviparous.this instanceof Otter) 
                this.time_end = Otter.TIME_GESTATION;
            else
                this.time_end = 0;
            this.time_left = this.time_end;
            this.e = e;
            this.b =b;

            this.isWorking = true;
            new Thread(this).start();
        }

        public Viviparous[] getBabies()
        {
            return this.babies;
        }

        public boolean isWorking()
        {
            return this.isWorking;
        }

        public void stop()
        {
            if(this.time_left == 0)
            {
                Thread.currentThread().stop();
                this.isWorking = false;
                System.out.println("Gestation ended");

                Viviparous.this.calve(this.e); //calving in Enclosure e.
            }
        }

        public void run() 
        {
            while(this.isWorking)
            {
                this.time_left--;
                try 
                {
                    Thread.sleep(400L);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
                if((this.time_left)%10==0 && this.time_left != 0)
                    System.out.println("Gestation will end in "+this.time_left+" days.");
            }
        }

}

我想在 time_left == 0 时触发 stop()。 就在我没有 stop() 方法之前,只有 run() ,其中当 time_left == time_end 时循环停止,然后调用 Viviparous.this 的 calve() ,最后一个方法要求用户通过输入为婴儿命名。 问题是我的程序已经要求用户从当前菜单中选择一个选项: 我猜输入婴儿姓名和菜单选项之间存在冲突。

最佳答案

I want the thread to stop automatically.

当线程的 run 方法返回或抛出异常时,线程将停止。如果您希望线程停止,请使其从 run() 返回。

如果您希望它在 time_left == 0 时自动停止,则在线程的顶级循环中测试 time_left,并让它在 time_left 时返回== 0.

关于java - 如何自动调用方法来停止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36892909/

相关文章:

c# - 分配的值未在任何执行路径中使用 - C#

java - Linux 上的 Gradle "cannot find Tools.jar"

java - groovy 中的静态属性拦截

java - XMPP注册新用户

.net - 多次加载 Dll 以允许 .Net 中的多线程

javascript - 浏览器中的JavaScript是否可能发生并发读/写读/写冲突?

PHP 公共(public)函数的行为类似于静态

typescript - 我应该在构造函数中抛出异常吗

java - Tomcat 因 JDK 中的 native 代码为 malloc_consolidate 而崩溃

multithreading - JavaFX TableView 更新频繁