一个新的线程创建之后通过start()方法进入到运行状态,在运行状态中可以使用yield()进行礼让,但是仍然可以进行,如果现在一个线程需要暂停的话,可以使用suspend(),sleep(),wait(),如果现在在线程不需要再执行,可以通过stop结束(如果run()方法执行完毕也表示结束),或者一个新的线程直接调用stop()方法也可以进行结束。
以上有如下的几个方法:
suspend();暂时挂起线程
resume();回复挂起的线程
stop();停止线程
因为以上三个方法都会产生死锁的问题。所以现在已经不建议使用了。
如果现在假设要想停止一个线程的运行该如何去做呢?
通过设置标志位,让线程停止运行。
以上有如下的几个方法:
suspend();暂时挂起线程
resume();回复挂起的线程
stop();停止线程
因为以上三个方法都会产生死锁的问题。所以现在已经不建议使用了。
如果现在假设要想停止一个线程的运行该如何去做呢?
通过设置标志位,让线程停止运行。
class MyThread implements Runnable{
private boolean flag = true;
public void run(){
int i=0;
while(this.flag){
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(); //启动线程
try{
Thread.sleep(30);
}catch(Exception e){
}
my.stop(); //修改标志符停止运行
}
}