/*使用两种方法实现停止一个线程。(stop()方法已不推荐使用。)
* 1.使用interrupt()方法停止一个线程。
* 2.使用notify()方法停止一个线程。
*
* */
public class Demo3 extends Thread{
int i=0;
boolean flag=true;
public Demo3(String name){
super(name);
}
public synchronized void run(){
while(flag){
System.out.println(Thread.currentThread().getName()+"i的值是"+i);
i++;
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("捕获到异常!");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo3 d =new Demo3("线程");
d.start();
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":i的值是"+i);
if(i==80){
d.flag=false;
//d.interrupt();//使用interrupt()方法停止一个线程。
synchronized(d){//使用notify()方法停止一个线程。
d.notify();
}
}
}
}
}
Java中两种停止线程的方法
最新推荐文章于 2024-12-03 23:02:05 发布
本文介绍了一种在Java中实现线程停止的方法。通过使用interrupt()和notify()方法,可以有效地控制线程的运行状态。示例代码展示了如何利用这些方法在特定条件下停止线程。
8355

被折叠的 条评论
为什么被折叠?



