IT干货网

java中的线程停止

luoye 2022年03月12日 编程设计 191 0

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时,线程确实停止。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!