publicclass stopTest implementsRunnable{//1.设置一个标志位privateboolean flag =true;@Overridepublicvoidrun(){int i =0;while(flag){System.out.println("run......Thread"+i++);}}//2.设置公开的方法停止线程,转换标志位publicvoidstop(){this.flag =false;}publicstaticvoidmain(String[] args){
stopTest stopTest =newstopTest();newThread(stopTest).start();for(int i =0; i <1000; i++){System.out.println("main"+i);if(i ==900){//调用stop方法切换标志位,使线程停止
stopTest.stop();System.out.println("线程该停止了");}}}}
2.线程休眠(sleep)
指定当前线程阻塞的毫秒数
存在异常(InterruptedException)
当达到时间后线程进入就绪状态
可模拟网络延时,倒计时
每个对象都有一个锁,sleep不会释放锁
代码模拟延时效果
//模拟倒计时publicclass sleep02Test {publicstaticvoidmain(String[] args)throwsInterruptedException{countDown();}publicstaticvoidcountDown()throwsInterruptedException{int num =10;while(true){Thread.sleep(1000);System.out.println(num--);if(num <=0){break;}}}}
publicclass joinTest implementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <300; i++){System.out.println("VIP is coming !"+i);}}publicstaticvoidmain(String[] args)throwsInterruptedException{
joinTest test =newjoinTest();Thread thread =newThread(test);//代理模式
thread.start();//主线程for(int i =0; i <1000; i++){if(i ==200){
thread.join();}System.out.println("main"+i);}}}
线程状态观测
代码实例
publicclass stateTest {publicstaticvoidmain(String[] args)throwsInterruptedException{Thread thread =newThread(()->{for(int i =0; i <10; i++){try{Thread.sleep(1000);}catch(InterruptedException e){
e.printStackTrace();}}System.out.println("******");});//观察状态Thread.State state = thread.getState();//变量System.out.println(state);//NEW//观察启动后
thread.start();
state = thread.getState();//变量System.out.println(state);//RUN//只要线程不会终止,就执行while语句while(state !=Thread.State.TERMINATED){Thread.sleep(1000);
state = thread.getState();//更新线程状态System.out.println(state);//输出状态}
thread.start();//报错,死亡的线程不能被启动}}