代替Thread.stop()终止线程的方法

方法一

自行决定线程何时退出

定义一个标记变量stopme,用于指示线程是否需要退出。当stopMe()被调用,代码检测到这个改动时,线程就退出了。

...
//线程内

volatile boolean stopme = false;

public void stopMe(){
	stope = true;
}

@Override
public void run(){
	while(true){
		if(stopme){
			System.out.println("exit by stop me");
			break;
		}
		//你要执行的代码
		...
	}
}
//线程内
...

方法二

用线程中断

与方法一比中断的功能更强,比如在 wait()或sleep()中只能用中断。

...
//main方法内

volatile boolean stopme = false;

public void stopMe(){
	stope = true;
}
Thread t1 = new Thread(){
	@Override
	public void run(){
		while(true){
			if(Thread.currentThread().isInterrupted()){
				System.out.println("interrupted");
				break;
			}
			//你要执行的代码
			...
		}
	}
};
t1.start();
Thread.sleep(2000);
t1.interrupt();

//main方法内
...

Thread.sleep()方法由于中断而抛出异常,此时会清除中断标记,如果不加以处理,那么在下一次循环开始时,就无法捕获这个中断,故需要再次设置中断标记。

...
//main方法内

volatile boolean stopme = false;

public void stopMe(){
	stope = true;
}
Thread t1 = new Thread(){
	@Override
	public void run(){
		while(true){
			if(Thread.currentThread().isInterrupted()){
				System.out.println("interrupted");
				break;
			}
			try{
				Thread.sleep(2000);
			}catch(InterruptedException e){
				System.out.println("interrupted when sleep");
				/再次设置中断标记
				Thread。currentThread().interrupt();
			}
			Thread.yield();
			}
		}
	}
};
t1.start();
Thread.sleep(2000);
t1.interrupt();

//main方法内
...

你可能感兴趣的:(java,并发)