java multithreading - thread termination

Two ways to terminate threads:
the thread is finished normally
external interference added identity (in the case really was executed for the next thread)
Do not use the stop and destroy methods

public class hh implements Runnable {
 //加入标识,标记线程体是否可以运行

private boolean flag=true;
private String name;
public hh(String name)
{
    this.name=name;
}
public void run()
{
    int i=0;
    //关联标识,true-->运行,false-->停止
    while(flag)
    {
        System.out.println(name+"-->"+i++);
    }
}
//对外提供方法改变标识
public void stopFlag()
{
    this.flag=false;
}
public static void main(String[]args)
{
    hh h=new hh("me");
    new Thread(h).start();

    for(int i=0;i<=10;i++)
    {
        if(i==9)
        {
            h.stopFlag();//线程的终止
            System.out.println("over");
        }
        System.out.println("it"+i);
    }

}

}

Guess you like

Origin blog.51cto.com/14437184/2427744