Java learning summary: 30

Thread life cycle

Thread life cycle
suspend () method: temporarily suspend the thread;
resume () method: resume the suspended thread;
stop () method: stop the thread.

The above three methods are not recommended for use, they have been slowly abolished, the main reason is that these three methods are prone to deadlock problems when used.
Since the above three methods are not recommended, we can stop the running of a thread by setting the flag bit in the development of the thread (this is also mentioned in the classic thread operation case in the previous section).

Example: Stop running the thread

package Project.Study.Multithreading;

class MyThread9 implements Runnable{
    private boolean flag=true;			//定义标志位属性
    public void run(){					//覆写run()方法
        int i=0;
        while(this.flag){				//循环输出
            while(true){
                System.out.println(Thread.currentThread().getName()+"运行,i="+(i++));
            }
        }
    }
    public void stop(){					//编写停止方法
        this.flag=false;				//修改标志位
    }
}
public class Test13 {
    public static void main(String []args){
        MyThread9 mt=new MyThread9();	//实例化Runnable接口对象
        Thread t=new Thread(mt,"线程");	//建立线程对象
        t.start();						//启动线程
        mt.stop();						//线程停止,修改标志位
    }
}
//结果:
//(无)
49 original articles published · Liked 25 · Visits 1518

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/105092454