【问题标题】:How do i stop a thread in java? [duplicate]如何在java中停止线程? [复制]
【发布时间】:2015-09-14 09:01:22
【问题描述】:

我有一个计时器线程:

Thread updateTimerThread = new Thread(new Runnable()
    {
            @Override
            public void run()
            {
                long updatedTime = 0L;
                long timeInMilliseconds = 0L;
                timeInMilliseconds = SystemClock.uptimeMillis() - startTime;//System.currentTimeMillis() - startTime;
                updatedTime = timeSwapBuff + timeInMilliseconds;
                int secs = (int) (updatedTime / 1000);
                int mins = secs / 60;
                secs = secs % 60;
                int milliseconds = (int) (updatedTime % 1000);
                timerValue.setText("" + mins + ":"
                        + String.format("%02d", secs) + ":"
                        + String.format("%03d", milliseconds));
                customHandler.postDelayed(this, 100);

                //updateTimerThread.start();
            }
    });

我是这样开始的:

updateTimerThread.start();

然后我试着阻止它:

updateTimerThread.stop();

但我在工位上看到一条黑线。

我的问题是这样好吗?停靠点上方的这条黑线是什么? 也许我需要使用其他东西然后停止?

我需要它做的是,当我点击停止它时,它会暂停停留在它到达的时间,当我再次点击开始时,它会再次启动计时器。

所以也许我不需要 stop 也许以某种方式暂停它? 当我再次启动时,它会重置它并从头开始?

【问题讨论】:

  • 1.在线程中声明一个布尔运行“isRunning”。 2. 在 run() 方法之前将该变量设置为“true”。 3. run() 方法中有条件:while (isRunning) 4. 当你想停止线程时,将 isRunning 设为 false。

标签: java


【解决方案1】:

一旦你正在做的工作完成,让它退出run() 方法。无需显式停止线程。

【讨论】:

    猜你喜欢
    • 2013-11-22
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多