@Deprecated(since="1.2")
public final void stop() {
@SuppressWarnings("removal")
SecurityManager security = System.getSecurityManager();
if (security != null) {
checkAccess();
if (this != Thread.currentThread()) {
security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
}
}
// A zero status value corresponds to "NEW", it can't change to
// not-NEW because we hold the lock.
if (threadStatus != 0) {
resume(); // Wake up thread if it was suspended; no-op otherwise
}
// The VM can handle all thread states
stop0(new ThreadDeath());
}
public class NumberCounter {
//要保存的数字
private volatile int number=0;
//数字计数器的逻辑是否完整
private volatile boolean flag = false;
public synchronized int increaseNumber() throws InterruptedException {
if(flag){
//逻辑不完整
throw new RuntimeException("逻辑不完整,数字计数器未执行完毕");
}
//开始执行逻辑
flag = true;
//do something
Thread.sleep(5000);
number++;
//执行完毕
flag=false;
return number;
}
}
public static void main(String[] args) throws InterruptedException {
NumberCounter numberCounter= new NumberCounter();
Thread thread = new Thread(()->{
while (true){
try {
numberCounter.increaseNumber();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
Thread.sleep(3000);
thread.stop();
numberCounter.increaseNumber();
}
Exception in thread "main" java.lang.RuntimeException: 逻辑不完整,数字计数器未执行完毕
at com.flydean.NumberCounter.increaseNumber(NumberCounter.java:12)
at com.flydean.Main.main(Main.java:18)
public static void main(String[] args) throws InterruptedException {
NumberCounter numberCounter = new NumberCounter();
Thread thread = new Thread(() -> {
while (true) {
try {
numberCounter.increaseNumber();
} catch (InterruptedException e) {
System.out.println("捕获InterruptedException");
throw new RuntimeException(e);
}
}
});
thread.start();
Thread.sleep(500);
thread.interrupt();
numberCounter.increaseNumber();
}
Exception in thread "main" Exception in thread "Thread-0" java.lang.RuntimeException: 逻辑不完整,数字计数器未执行完毕
at com.flydean.NumberCounter.increaseNumber(NumberCounter.java:12)
at com.flydean.Main2.main(Main2.java:21)
java.lang.RuntimeException: java.lang.thread.interrupt: sleep interrupted
at com.flydean.Main2.lambda$main$0(Main2.java:13)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at com.flydean.NumberCounter.increaseNumber(NumberCounter.java:17)
at com.flydean.Main2.lambda$main$0(Main2.java:10)
... 1 more
捕获InterruptedException
if (Thread.interrupted()) // Clears interrupted status!
throw new InterruptedException();
public void run () {
try {
while (true) {
// do stuff
}
}catch (InterruptedException e) {
LOGGER.log(Level.WARN, "Interrupted!", e);
// Restore interrupted state...
Thread.currentThread().interrupt();
}
}