线程创建
Thread t = new Thread();
线程对象一旦创建就进入到了新生状态
就绪状态
当调用start()方法,线程立即进入就绪状态,但不意味着立即调度执行
运行状态
进入运行状态,线程才真正执行线程体的代码块
阻塞状态
当调用sleep,wait或同步锁定时,线程进入阻塞状态,就是代码不往下执行,阻塞事件解除后,重新进入就绪状态,等待cpu调度。
- sleep(时间)指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedException;
- sleep时间到达后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等;
- 每一个对象都有一个锁,sleep不会释放锁
//模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable{
private int ticketNums = 5;
@Override
public void run() {
while(ticketNums>0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestSleep testSleep = new TestSleep();
new Thread(testSleep,"小明").start();
new Thread(testSleep,"小红").start();
new Thread(testSleep,"黄牛").start();
}
}
//模拟倒计时
public class TestSleep2 {
public static void main(String[] args) throws InterruptedException {
//打印系统当前时间
Date startTime = new Date(System.currentTimeMillis());
while(true){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());
}
}
//不准确,因为CPU调度需要时间
public static void tenDown() throws InterruptedException {
int num = 10;
while(num>0){
Thread.sleep(1000);
System.out.println(num--);
}
}
死亡状态
线程中断或者结束,一旦进入死亡状态,就不能再次启动。
- 1.建议线程正常停止–>利用次数,不建议死循环
- 2.建议使用标志位–>设置一个标志位
- 3.不要使用stop或者destory等过时或者jdk不建议使用的方法
public class TestStop implements Runnable{
//设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run....Thread"+i++);
}
}
//自定义停止方法。
public void stop(){
this.flag = false;
}
public static void main(String[] args) throws InterruptedException {
TestStop testStop = new TestStop();
new Thread(testStop).start();
Thread.sleep(2);
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
状态的测试
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) {
e.printStackTrace();
}
}
System.out.println("/");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//启动后
thread.start();
state = thread.getState();
//只要线程不终止,就一直输出状态
while(thread.getState() != Thread.State.TERMINATED){
Thread.sleep(1000);
state = thread.getState();
System.out.println(state);
}
}
}