1:如果你从run方法返回了,那个线程本身就销毁了。
2:你可以调用线程类的.stop()方法,不过应该避免使用这种办法,因为会造成虚机垃圾回收的问题,具体见2例
3:你也可以用一个boolean变量来实现.stop()方法,具体见3例
2例:
public class DeprecatedStop extends Object implements Runnable { public void run() {
int count = 0; while ( true ) { System.out.println("Running ... count=" + count);
count++;
try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
// ignore
}
}
} public static void main(String[] args) {
DeprecatedStop ds = new DeprecatedStop();
Thread t = new Thread(ds);
t.start(); try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
// Abruptly stop the other thread in its tracks!
t.stop();
}
}
///////////////////////////////////////////////
///////////////////////////////////////////////
3例:
public class AlternateStop extends Object implements Runnable {
private volatile boolean stopRequested;
private Thread runThread; public void run() {
runThread = Thread.currentThread();
stopRequested = false; int count = 0; while ( !stopRequested ) {
System.out.println("Running ... count=" + count);
count++; try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt(); // reassert
}
}
} public void stopRequest() {
stopRequested = true; if ( runThread != null ) {
runThread.interrupt();
}
} public static void main(String[] args) {
AlternateStop as = new AlternateStop();
Thread t = new Thread(as); t.start(); try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
as.stopRequest(); } }
2:你可以调用线程类的.stop()方法,不过应该避免使用这种办法,因为会造成虚机垃圾回收的问题,具体见2例
3:你也可以用一个boolean变量来实现.stop()方法,具体见3例
2例:
public class DeprecatedStop extends Object implements Runnable { public void run() {
int count = 0; while ( true ) { System.out.println("Running ... count=" + count);
count++;
try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
// ignore
}
}
} public static void main(String[] args) {
DeprecatedStop ds = new DeprecatedStop();
Thread t = new Thread(ds);
t.start(); try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
// Abruptly stop the other thread in its tracks!
t.stop();
}
}
///////////////////////////////////////////////
///////////////////////////////////////////////
3例:
public class AlternateStop extends Object implements Runnable {
private volatile boolean stopRequested;
private Thread runThread; public void run() {
runThread = Thread.currentThread();
stopRequested = false; int count = 0; while ( !stopRequested ) {
System.out.println("Running ... count=" + count);
count++; try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt(); // reassert
}
}
} public void stopRequest() {
stopRequested = true; if ( runThread != null ) {
runThread.interrupt();
}
} public static void main(String[] args) {
AlternateStop as = new AlternateStop();
Thread t = new Thread(as); t.start(); try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
as.stopRequest(); } }
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货