java中的线程停止
java中的线程停止
以下代码展示如何设置让运行的线程停止:
package com.cxf.multithread.stop;
public class TestForStop implements Runnable{
private boolean flag = true;
public static void main(String[] args) {
TestForStop testForStop =new TestForStop();
Thread thread1 = new Thread(testForStop);
thread1.start();
for (int i = 0; i <= 3; i++) {
System.out.println("counting"+i);
}
testForStop.stop();
}
public void stop(){
this.flag = false;
}
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("i am running"+i++);
}
}
}
这里的线程停止实际上是让线程跳出自己所写的循环,提前完成任务。
输出结果:
counting0
i am running0
i am running1
counting1
counting2
counting3
i am running2
从结果可见数到3时,线程确实停止。