12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import java.util.concurrent.*;
- public class TestInterrupt {
- public static void main(String[] args) {
- InterruptThread thread = new InterruptThread();
- thread.start();
- try {
- Thread.sleep(500);
- } catch (Exception e) {
- e.printStackTrace();
- }
- thread.interrupt();
- ExecutorService executor = Executors.newFixedThreadPool(1);
- executor.execute(() -> {
- System.out.println("Thread start!");
- try {
- Thread.sleep(1000);
- } catch (Exception e) {
- e.printStackTrace();
- }
- });
- executor.shutdownNow();
- executor = Executors.newFixedThreadPool(1);
- Future<?> future = executor.submit(new InterruptThread());
- future.cancel(true);
- executor.shutdown();
- }
- }
- class InterruptThread extends Thread {
- @Override
- public void run() {
- while (!interrupted()) {
- System.out.println("Thread is running.");
- try {
- Thread.sleep(1000);
- } catch (Exception e) {
- e.printStackTrace();
- return;
- }
- }
- System.out.println("Thread end.");
- }
- }
|