Sesuatu benang boleh mengganggu benang dengan menghantar isyarat sampukan dengan memanggil kaedah interrupt() objek benang. Ini bermakna gangguan benang disebabkan oleh urutan lain yang memanggil kaedah interrupt(). Kelas
Thread menyediakan tiga kaedah gangguan:
public class ThreadInterruptTest { public static void main(String[] args) { System.out.println("Thread main started"); final Task task = new Task(); final Thread thread = new Thread(task); thread.start(); thread.interrupt(); // calling interrupt()<strong> </strong>method System.out.println("Main Thread finished"); } } class Task implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("[" + Thread.currentThread().getName() + "] Message " + i); if(Thread.interrupted()) { System.out.println("This thread was interruped by someone calling this Thread.interrupt()"); System.out.println("Cancelling task running in thread " + Thread.currentThread().getName()); System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted()); break; } } } }
Thread main started Main Thread finished [Thread-0] Message 0 This thread was interruped by someone calling this Thread.interrupt() Cancelling task running in thread Thread-0 After Thread.interrupted() call, JVM reset the interrupted value to: false
Atas ialah kandungan terperinci Bagaimana untuk mengganggu thread yang sedang berjalan di Java?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!