状态图
ready to run 就绪态,可以抢占资源的线程
blocked:阻塞,被I/O或者进入同步代码块而阻塞
sleep:超时等待,当一定时间过了之后会进入就绪态
waiting:等待,如果不被notify唤醒将永远等待
sleep
public class NewThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
System.out.println("自定义的线程执行");
try {
// sleep线程超时等待100ms,过了时间后线程进入就绪态
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(new NewThread());
thread.start();
while (true) {
System.out.println("主线程执行 ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
wait
public class NewThread2 implements Runnable{
@Override
public synchronized void run() {
// TODO Auto-generated method stub
while (true) {
try {
// wait线程进入等待,直到notifyall才能进入就绪态
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("自定义的线程执行");
}
}
public static void main(String[] args) {
NewThread2 n = new NewThread2();
Thread thread = new Thread(n);
thread.start();
while (true) {
synchronized (n) {
System.out.println("主线程执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
n.notifyAll();
}
}
}
}