packagecom.xct.test;//测试线程停止publicclassTestStopimplementsRunnable{//设置标志位privateboolean flag =true;@Overridepublicvoidrun(){int i =0;while(flag){System.out.println("线程启动"+i++);}}//停止线程publicvoidstop(){this.flag =false;}publicstaticvoidmain(String[] args){TestStop testStop =newTestStop();newThread(testStop).start();for(int i =0; i <1000; i++){System.out.println("main"+i);if(i ==900){//切换标志位,让线程停止
testStop.stop();System.out.println("线程该停止了");}}}}
线程休眠sleep
1.sleep指当前线程阻塞的毫秒数。
2.sleep存在异常InterruptedException。
3.sleep时间达到后线程进入就绪状态。
4.每个对象都有一把锁,sleep不会释放锁。
示例:通过sleep设置倒计时
packagecom.xct.test2;//通过sleep设置倒计时publicclassTestSleep{publicstaticvoidmain(String[] args)throwsInterruptedException{int num =10;while(true){Thread.sleep(1000);System.out.println(num);
num--;if(num<0){break;}}}}
packagecom.xct.test2;//练习join插队publicclassTestJoinimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <800; i++){System.out.println("vip"+i);}}publicstaticvoidmain(String[] args)throwsInterruptedException{Thread thread =newThread(newTestJoin());
thread.start();//主线程for(int i =0; i <500; i++){if(i ==200){
thread.join();}System.out.println("普通用户"+i);}}}
总结
示例:查看线程状态
packagecom.xct.test2;//查看线程状态publicclassTestState{publicstaticvoidmain(String[] args)throwsInterruptedException{Thread thread =newThread(()->{for(int i =0; i <5; i++){try{Thread.sleep(1000);}catch(InterruptedException e){
e.printStackTrace();}System.out.println("/");}});//观察状态Thread.State state = thread.getState();System.out.println(state);//观察启动后的状态
thread.start();
state = thread.getState();System.out.println(state);//只要线程一直不中止,就一直输出状态while(state !=Thread.State.TERMINATED){Thread.sleep(1000);//更新线程状态
state = thread.getState();System.out.println(state);}}}