线程中断

来源:互联网 发布:和莎莫的500天 知乎 编辑:程序博客网 时间:2024/04/29 08:54

线程中断:通过设置标记来中断线程,不要使用interrupt()方法

public class InterruptedDemo {

public static void main(String[] args) {
RunnableIn rin = new RunnableIn();
Thread thread = new Thread(rin);
thread.start();
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i==10) {
rin.setFlag(false);  //修改标记
}
System.out.println(Thread.currentThread().getName()+"正在听第"+(i)+"首歌!");
}
}


}
class RunnableIn implements Runnable{
int i = 0;
boolean flag = true;
public void setFlag(boolean flag){
this.flag = flag;
}

@Override
public void run() {
while(flag && i<20){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在下载第"+(i++)+"首歌!");
}
}

}
0 0
原创粉丝点击