多线程停止的方法

线程停止有基本的两种思路:

执行stop()函数,但是不够安全,这是一个强制结束线程的方式,

任务结束,自己停止。(常用方法)

1.标记停止的方法。

弊端:在多个线程的情况下,当有一个线程处于等待状态时,此时停止线程,则无法停止处于等待中的线程。

示例:设置标记flag,控制线程结束。

class StopThread implements Runnable{
private boolean flag = true;
public void run (){
while(flag){
System.out.println(Thread.currentThread().getName()+"run ");
}
}

public void setFlag(){
this.flag =false;;

}
}

class ProduceDemo{
public static void main(String[] arg){

StopThread stop = new StopThread();
Thread t1 = new Thread(stop);
Thread t2 = new Thread(stop);
t1.start();
t2.start();
int i = 0;
while(true){
if(i == 50){
stop.setFlag();
break;
}
System.out.println("main");
i++;
}
}
}

下面这种用标记法就不行,就算标记设置为了false,但是出于wait中的线程无法结束任务。

class StopThread implements Runnable{
private boolean flag = true;

public synchronized void run (){
while(flag){
try{
wait();
}
catch(Exception e){
System.out.println("Exception ");
};
System.out.println(Thread.currentThread().getName()+"********");
}

}
public void setFlag(){
this.flag =false;

}


}

class ProduceDemo{
public static void main(String[] arg){

StopThread stop = new StopThread();
Thread t1 = new Thread(stop);
Thread t2 = new Thread(stop);
t1.start();
t2.start();

int i = 0;
while(true){
if(i == 50000){
stop.setFlag();
break;
}

i++;
}
System.out.println("over");
}
}

2.interrupt方法

线程处于冻结状态无法获取标记,如何结束呢?

可以使用interrupt()方法将线程从冻结状态强制恢复到运行状态中来,让线程具备CPU的执行资格。

强制动作会发生interruptException,记得处理。

class StopThread implements Runnable{
private boolean flag = true;

public synchronized void run (){
while(flag){
try{
wait();
}
catch(Exception e){
System.out.println("Exception ");
flag = false;
};
System.out.println(Thread.currentThread().getName()+"********");
}

}
public void setFlag(){
this.flag =false;

}


}

class ProduceDemo{
public static void main(String[] arg){

StopThread stop = new StopThread();
Thread t1 = new Thread(stop);
Thread t2 = new Thread(stop);
t1.start();
t2.start();

int i = 0;
while(true){
if(i == 50000){
t1.interrupt();
t2.interrupt();
break;
}

i++;
}
System.out.println("over");
}
}

猜你喜欢

转载自www.cnblogs.com/chzlh/p/9278611.html