线程没有停止

时间:2013-12-31 21:16:15

标签: java multithreading

所以我有一个线程,在那个线程中我声明了一个像这样的布尔值:

volatile boolean stopThread = false;

然后在我的帖子中看起来像这样:

public void run() {

    while (!stopThread) {

        while (i < list.size()) {
            System.out.println(list.get(i));
        }

    }

}

线程的启动方式如下:

t1 = new CheckThread();
t2 = new CheckThread();

每件事都运行正常,但我想允许用户停止线程,所以我创建了一个按钮并添加了以下两行:

t1.stopThread = true;
t2.stopThread = true;

但是当我点击按钮时,线程仍会运行。我也试过以下

CheckThread.stopThread = true;

但这也不起作用。 为什么我的帖子没有停止?

编辑:

我这样开始我的线程。我有一个类,除了我有这两个变量的任何方法

CheckThread t1;
CheckThread t2;

单击该按钮时,我会执行以下操作

t1 = new CheckThread();
t2 = new CheckThread();

t1.start();
t2.start();

我知道线程正在运行,因为我在线程中有一个print语句。

2 个答案:

答案 0 :(得分:0)

必须做的是在第二个while循环中添加另一个条件,所以它看起来像这样

while (i < list.size() && !stopThread) {
    System.out.println(list.get(i));
}

这会在停止线程时从第二个退出。

答案 1 :(得分:0)

我没有看到i的值不断变化,所以我假设你的内循环是无限的。我不确定你对列表的意图是什么,但重点是看到输入内循环后,stopThread的值无关紧要。

也许这个(改变i的值):

while (!stopThread) {

    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

或者像这样(没有内循环):

while (!stopThread) {

    if (i < list.size()) {
        System.out.println(list.get(i));
    }
}

或者这个(没有内循环):

while (!stopThread && i < list.size()) {

    System.out.println(list.get(i));
}
相关问题