Java 多线程停止 定义标记

xiaoxiao2021-02-27  102

/* 停止线程: 1 stop 方法。 2 run 方法结束 怎么控制线程的任务结束? 任务中都会有循环结构(没有循环就不需要多线程了,开多线程就是怕这里循环影响其他),只要控制住循环就可以结束任务 控制循环通常就用定义标记来完成 */ class StopThread implements Runnable{ private boolean flag=true; public void run(){ while(flag){ System.out.println(Thread.currentThread().getName()+"...."); } } public void setFlag(){ flag=false; } } class StopThreadDemo{ public static void main(String[] args) { StopThread st=new StopThread(); Thread t1=new Thread(st); Thread t2=new Thread(st); t1.start(); t2.start(); int num=1; for(;;){ if(++num==50){ st.setFlag();//此处将标记变为false 停止线程 break; } System.out.println("main..."+num); } } }
转载请注明原文地址: https://www.6miu.com/read-16011.html

最新回复(0)