状态:
new
就绪
运行
阻塞
死亡
停止:
不推荐jdk的stop(),destory();推荐线程自己停下来;设置标识位终止变量,当flag=flase,线程终止
package com.wuming.state;
public class TestStop implements Runnable{
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
//1.设置一个标识位
private boolean flag=true;
@Override
public void run() {
int i=0;
while(flag){
System.out.println("run...Thread"+i++);
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
main0 main1 main2 main3 main4 main5 main6 main7 main8 main9 main10 main11 main12 main13 main14 main15 main16 main17 main18 main19 main20 main21 main22 main23 main24 main25 main26 main27 main28 main29 main30 main31 main32 main33 main34 main35 main36 main37 main38 main39 main40 main41 main42 main43 main44 main45 main46 main47 main48 main49 main50 线程停止了 main51 main52 main53 main54 main55 main56 main57 main58 main59 main60 main61 main62 main63 main64 main65 main66 main67 main68 main69 main70 main71 main72 main73 main74 main75 main76 main77 main78 main79 main80 main81 main82 main83 main84 main85 main86 main87 main88 main89 main90 main91 main92 main93 main94 main95 main96 main97 main98 main99
|