new-》就绪状态 -》运行状态-》阻塞状态-》dead
线程休眠(sleep)
模拟网络延时,放大问题的发生性
import java.text.SimpleDateFormat;
import java.util.Date;
public class SleepTest {
public static void main(String[] args) {
//获取系统当前时间
Date date=new Date(System.currentTimeMillis());
while(true) {try {
//每一秒输出一次
Thread.sleep(1000);
//格式化系统时间
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
//更新当前时间
date=new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
}
线程礼让(yield)
让当前正在执行的线程暂停,但不阻塞。将线程从运行状态 转为就绪状态。
让cpu重新调度,礼让不一定成功。
public class ThreadYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止");
}
public static void main(String[] args) {
ThreadYield yield=new ThreadYield();
new Thread(yield,"线程1").start();
new Thread(yield,"线程2").start();
}
}
线程强制执行(join)
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞。(可以想象成插队)
public class ThreadJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("子线程来了");
}
}
public static void main(String[] args) throws InterruptedException {
//开启线程
ThreadJoin join=new ThreadJoin();
Thread thread=new Thread(join);
thread.start();
//主线程
for (int i = 0; i < 100; i++) {
if (i==20){
thread.join();
}
System.out.println("main"+i);
}
}
}
观测线程状态
public class ThreadState {
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();
System.out.println(state);
//只要线程不被ko,就一直观察
while(state!=Thread.State.TERMINATED){
//添加阻塞
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}
来源:b站狂神学习,用作笔记