在Java中一个线程对象都有自己的生命周期,如果要控制好线程的生命周期,则首先应认识其生命周期。
从图中可以看出,大部分的线程生命周期的方法基本上都学过了。
线程的操作方法
其中三个新的方法如下:
1. suspend()方法:暂时挂起线程。
2. resume()方法:恢复挂起的线程。
3. stop()方法:停止线程。
但是对于线程中suspend()、resume()、stop()方法并不推荐使用。因为这三种方法在线程操作时会产生死锁问题。既然不推荐使用,在多线程的开发中可以通过设置标志位的方式停止一个线程的运行。
【停止线程运行】
class MyThread implements Runnable
{
private boolean flag=true;
public void 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 StopDemo
{
public static void main(String args[])
{
MyThread my=new MyThread();
Thread t=new Thread(my,"线程");
t.start();
my.stop();
}
}
以上程序一点调用stop()方法就会将MyThread类中的flag变量设置为false,这样run方法就会停止运行,这种停止方式在开发中比较常用。