关于interrupt的使用挺简单的,一则代码就知道了。
package Day03;
/**
* 中断睡眠阻塞
* @author Administrator
*
*/
public class InterruptSleepBlockDemo {
public static void main(String[] args) {
/*
* lin,处于睡眠阻塞的线程
*/
final Thread lin = new Thread(new Runnable(){
public void run() {
System.out.println("lin:hahahaha");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
System.out.println("lin:what are you fucking doing?");
}
}
});
/*
* huang,用于中断lin的睡眠阻塞
*/
Thread huang = new Thread(new Runnable(){
public void run() {
System.out.println("开始砸!");
for (int i = 0; i < 5; i++) {
System.out.println("80!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
System.out.println("BOW!!");
System.out.println("huang:OK!");
//终端lin的线程,打断其睡眠阻塞
/*
* 一个方法的局部内部类中若要引用该方法的其他局部变量,那么这个变量必须是final的
*/
lin.interrupt();
}
});
lin.start();
huang.start();
}
}
运行结果:
上面的例子其实可以用wait和notify来实现同样的效果:
package Day03;
/**
* 中断睡眠阻塞
* @author Administrator
*
*/
public class WaitAndNotifySleepBlockDemo {
public static void main(String[] args) {
final Thread huang = new Thread(new Runnable(){
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("开始砸!");
for (int i = 0; i < 5; i++) {
System.out.println("80!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
System.out.println("BOW!!");
System.out.println("huang:OK!");
synchronized (this) {
this.notify();
}
}
});
Thread lin = new Thread(new Runnable(){
public void run() {
System.out.println("lin:hahahaha");
synchronized (huang) {
try {
huang.wait();//将lin阻塞在huang的线程上,此时此线程阻塞等待唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("lin:what are you fucking doing?");
}
});
lin.start();
huang.start();
}
}