如何优雅的停止Java线程?

interrupt

package threadTest;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread a = new Thread(new Worker());
a.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.interrupt();
}
}
class Worker implements Runnable {
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
System.out.println(new Date());
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println(“Exited!”);
}
}
}

发表评论