以往有的时候会使用stop()方法停止线程,但是JDK早就已经废除了stop()方法,不建议使用stop()方法来停止一个线程的运行。
下面有两种方法实现线程的中断:
一:异常处理
/*
使用两种方法使程序中断
*/
/*1异常处理:package THREAD;
class Test extends Thread {
public void run() {
try {
Thread.sleep(100000000);
System.out.println("HelloWorld");
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName() + "-->"+i);
}
}
}这个意思就是先让程序一直睡眠,如果睡眠到了时间以后输出HelloWorld,使用中断让这个程序中断然后执行下面的for语句
public class interrupt {
public static void main(String[] args) throws InterruptedException {
Thread test = new Test();
test.start();//启动线程
Thread.sleep(5000);
test.interrupt();//执行中断
}
}*/
执行结果如下所示:
由于 Thread.sleep(100000000);睡眠时间太长了,CPU想执行其他的程序,就使用 test.interrupt();//执行中断,去执行下面的for语句就运行如下结果。
Thread-0-->0
Thread-0-->1
Thread-0-->2
Thread-0-->3
Thread-0-->4
Thread-0-->5
Thread-0-->6
Thread-0-->7
Thread-0-->8
Thread-0-->9
二:布尔值
//2:布尔值
package THREAD;
class Test implements Runnable{
boolean run=true;
public void run() {
for(int i=0;i<10;i++)
{
if(run)
{
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "-->"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else return;
}
}
}//如果run=true执行程序但是主程序中的 run是false所以先睡眠5秒然后执行重写的run程序
public class interrupt {
public static void main(String[] args) throws InterruptedException {
Test t1=new Test();
Thread t2 = new Thread(t1);
t2.start();//启动线程
Thread.sleep(5000);
t1.run=false;
}
}
运行结果如下所示:
Thread-0-->0
Thread-0-->1
Thread-0-->2
Thread-0-->3
Thread-0-->4
Thread.sleep()主线程休眠5秒,t2线程运行5次,t2执行一次间隔一秒,
所以执行到4.然后由于 t1.run=false;run()方法不能继续执行,所以结果如上所示。