a.使用volatile变量来设置Thread的run的循环条件,保证变量同步性
public class JavaTest extends Thread{
private volatile boolean isRun = true;
public static void main(String[] args) {
JavaTest thread = new JavaTest();
thread.start();
thread.close();
}
@Override
public void run() {
while (isRun) {
//dosomething
}
}
public void close() {
this.isRun = false;
}
}
b.使用interrupt()来中止非运行状态的线程,如wait()和sleep()状态的线程,此时可利用interrupted来终止线程
http://polaris.blog.51cto.com/1146394/372146/
public class JavaTest extends Thread{
private volatile boolean isRun = true;
public static void main(String[] args) {
JavaTest thread = new JavaTest();
thread.start();
thread.close();
}
@Override
public void run() {
while (isRun) {
//dosomething
}
}
public void close() {
this.isRun = false;
}
}
b.使用interrupt()来中止非运行状态的线程,如wait()和sleep()状态的线程,此时可利用interrupted来终止线程
http://polaris.blog.51cto.com/1146394/372146/