/*
1.讓各個對象或類相互靈活交流
2.兩個線程都凍結了,就不能喚醒了,因為根據代碼要一個線程活着才能執行喚醒操作,就像玩木游戲
3.中斷狀態就是凍結狀態
4.當主線程退出的時候,里面的兩個線程都處於凍結狀態,這樣就卡住了
5.try catch 有異常,catch就自動幫忙處理,程序繼續運行
6.讓wait 中斷 就會發生異常,就會被處理
*/
/*
stop方法已經過時。
如何停止線程?
只有一種,run方法結束。
開啟多線程運行,運行代碼通常是循環結構。
只要控制住循環,就可以讓run方法結束,也就是線程結束。
特殊情況:
當線程處於了凍結狀態。
就不會讀取到標記。那么線程就不會結束。
當沒有指定的方式讓凍結的線程恢復到運行狀態是,這時需要對凍結進行清除。
強制讓線程恢復到運行狀態中來。這樣就可以操作標記讓線程結束。
Thread類提供該方法 interrupt();
*/
class StopThread implements Runnable
{
private boolean flag =true;
public void run()
{
while(flag)
{
System.out.println(Thread.currentThread().getName()+"....run");
}
}
public void changeFlag()
{
flag = false;
}
}
class StopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.setDaemon(true); /*守護線程,也叫后台線程,主線程一掛,后台線程也跟着掛*/
t2.setDaemon(true);
t1.start();
t2.start();
int num = 0;
while(true)
{
if(num++ == 60)
{
//st.changeFlag();
//t1.interrupt();
//t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"......."+num);
}
System.out.println("over");
}
}