多线程(二)
线程的状态
-
创建状态
-
就绪状态
-
阻塞状态
-
运行状态
-
死亡狂态
如何停止线程
package base.duoxiancheng.Demo05; public class TestSop implements Runnable { private boolean flage=true; @Override public void run() { int i=0; while (flage){ System.out.println("线程运行在"+i++); } } public void stop(){ this.flage=false; } public static void main(String[] args) { TestSop testSop=new TestSop(); new Thread(testSop).start(); for (int i = 0; i <1000 ; i++) { if (i==900){ testSop.stop();} { System.out.println("运行中"+i); } } } }
建议让线程自己停下,建议设置一个标志位的终止变量,同个flag的true或者false来终止线程
线程的休眠 Sleep
sleep(设置休眠的毫秒值)
sleep需要有一个异常来抛出
sleep时间到达之后会让线程进入就绪状态
sleep用于模拟延迟或者倒计时
每个对象都有一把锁,但是sleep不会释放锁
模拟倒计时
package base.duoxiancheng.Demo06;
public class Sleeptest implements Runnable {
private boolean flag=true;
@Override
public void run() {
for (int i = 0; i <=10 ; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(+i);
if (i==10)
break;
}
}
public static void main(String[] args) {
Sleeptest sleeptest =new Sleeptest();
new Thread(sleeptest).start();
}
}
## 探知此时线程的状态
package base.duoxiancheng.Demo07;
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread =new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
System.out.println("/////");
});
Thread.State state = thread.getState();
System.out.println(state);
thread.start();
while (state!=Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}
运行结果
NEW
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
/////
TERMINATED
线程的优先级
thread.setPriority(优先级(1-10));
这个一定要在线程运行之前 thread.start之前