Cố gắng làm gián đoạn luồng đang chạy, trong ví dụ này, t1, được thực hiện bởi một luồng trong một nhóm luồng.Làm gián đoạn chủ đề đang ngủ
t2 là đoạn gửi ngắt.
Tôi không thể dừng chạy t1, t1 không nhận được InterruptedException.
Tôi đang thiếu gì?
Executor exec1 = Executors.newFixedThreadPool(1);
// task to be interrupted
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("starting uninterruptible task 1");
Thread.sleep(4000);
System.out.println("stopping uninterruptible task 1");
} catch (InterruptedException e) {
assertFalse("This line should never be reached.", true);
e.printStackTrace();
}
}
};
final Thread t1 = new Thread(runnable);
// task to send interrupt
Runnable runnable2 = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
t1.interrupt();
System.out.println("task 2 - Trying to stop task 1");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread(runnable2);
exec1.execute(t1);
t2.start();
t2.join();
Cảm ơn BegemoT. Điều này thật ý nghĩa. – portoalet
begemot đã làm đúng –