1:要使一个线程结束必须让其run方法执行完毕
一般来说run方法中执行的都是循环体,因此只要控制如何结束循环即可
备注:stop()方法可以结束线程但是已被废弃。
方法一:对于同步的run方法,在某种情况下会出现问题,需要用interrupt()来打断线程的wait状态
例子:
class InterruptDemo {
public static void main(String[] args) {
InterruptRunnable ir = new InterruptRunnable();
int num = 1;
Thread t1 = new Thread(ir);
Thread t2 = new Thread(ir);
t1.start();
t2.start();
while(true) {
if(num++ ==60) {
t1.interrupt();
t2.interrupt();
break;
}
}
System.out.println("main over");
}
}
class InterruptRunnable implements Runnable {
private boolean flag=true;
public synchronized void run() {