介绍java多线程例子
在Thread类中stop已经不推荐大家使用了,因为使用stop停止的线程不安全,它并不会释放被该线程锁定的对象的锁旗标,这样其它线程如果也想要得到该对象的锁旗标就永远得不到了,形成死锁了。
利用标志位控制线程的生命周期:
public class threadtest {
public static void main(String[] args) {
Thread1 t = new Thread1();
t.start();
try{Thread.sleep(1);}catch(Exception e){};
for(int i=0; i<10; i++) {
System.out.println("main"
+ " is running.");
if(i==5)
t.stopMe();
}
}
}
class Thread1 extends Thread {
private boolean bStop = false;
public void stopMe() {
this.bStop = true;
}
public void run() {
while(!bStop) {
System.out.println(Thread.currentThread().getName() + " is running.");
}
}
}
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说教育文库java多线程例子(16)在线全文阅读。
相关推荐: