interrupt()
If this thread is blocked in an invocation of the {@link
- Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
- Object#wait(long, int) wait(long, int)} methods of the {@link Object}
- class, or of the {@link #join()}, {@link #join(long)}, {@link
- #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
- methods of this class, then its interrupt status will be cleared and it
- will receive an {@link InterruptedException}.
翻译:
如果这个线程在调用{@link
- Object#wait() wait()}, {@link Object#wait(long) wait(long)},或{@link
{@link Object}的wait(long, int)方法
类,或{@link #join()}, {@link #join(long)}, {@link . *类
- #加入(长,int)}, {@link sleep#睡眠(长)}或{@link #睡眠(长,int)},
*方法,那么它的中断状态将被清除,并且它
*将收到一个{@link InterruptedException}。
用法:
在一个线程处于blocked阻塞状态去调用interrupt()方法时候,会中断线程并且使该线程直接结束(terminated)
但是当线程调用的方法是一个死循环,会清除中断后继续执行.
static String lock = "aa";
public void test() {
for (int i = 0; ; i++) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 5) {
try {
lock.wait();
// Thread.sleep(3000);
System.out.println(1111);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Demo2_1 demo2_1 = new Demo2_1();
Thread t1 = new Thread() {
@Override
public void run() {
synchronized (lock) {
demo2_1.test();
}
}
};
t1.start();
Thread t2 = new Thread() {
@Override
public void run() {
synchronized (lock) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// lock.notifyAll();
System.out.println("ok");
}
}
};
t2.start();
try {
Thread.sleep(4000);
t1.interrupt();
System.out.println(t1.getState());//waiting伴随着阻塞
// System.out.println(t2.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static String lock = "aa";
public void test() {
try {
for (int i = 0; ; i++) {
System.out.println(i);
Thread.sleep(500);
if (i == 5) {
lock.wait();
// Thread.sleep(3000);
System.out.println(1111);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
## 把循环内容放入try-catch中,线程就会进入死亡状态
public static void main(String[] args) throws InterruptedException {
Demo2_1 demo2_1 = new Demo2_1();
Thread t1 = new Thread() {
@Override
public void run() {
synchronized (lock) {
demo2_1.test();
}
}
};
t1.start();
Thread t2 = new Thread() {
@Override
public void run() {
synchronized (lock) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// lock.notifyAll();
System.out.println("ok");
}
}
};
t2.start();
try {
Thread.sleep(4000);
t1.interrupt();
Thread.sleep(1000);
System.out.println(t1.getState());//waiting伴随着阻塞
// System.out.println(t2.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}