目录
线程五大状态
new:Thread t=new Thread线程对象一单创建就进入到了新生状态
就绪状态:当调用start()方法,线程理级进入就绪状态,但不意味着理级调度执行
运行状态:进入运行状态,线程才正正执行线程体得代码块
阻塞状态:当调用sleep、wait或同步锁定时,线程进入锁定状态,就是代码不往下执行,阻塞事件解除后,重新进入就绪状态,等待CPU调度执行
dead:线程中断或者结束,一旦进入死亡状态,就不能再次启动
线程停止
不推荐使用JDK提供得stop()、destory方法(已废弃)
推荐线程自己停止下来
建议使用一个标标志位进行终止变量,放flag=false,则终止线程运行
//1,建议线程征程停止----利用次数,不建议死循环
//2.建议使用标志位
//3.不建议使用jdk得的stop和distory,已过时
public class TestThread6 implements Runnable {
//1,线程中定义线程体使用标志
private boolean flag=true;
@Override
public void run() {
//2.线程体使用标注
while (flag){
int i=0;
System.out.println("线程运行时"+i++);
}
}
//2设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestThread6 testThread6=new TestThread6();
new Thread(testThread6).start();
for(int i=0;i<100;i++){
if(i==50){
testThread6.stop();
System.out.println("线程停止==="+i);
}
System.out.println("main==="+i);
}
}
}
线程休眠
sleep(时间)指定当前线程阻塞的毫秒数(1000毫秒=1秒)
sleep存在异常InterruptedException;
sleep时间达到后线程进入就绪状态
sleep可以模拟网络延时,倒计时等
每个对象都有一个锁,sleep不会释放锁
模拟网络延时的作用:放大问题的发生性(比如之前笔记上的买票案例【多线程】线程创建-CSDN博客)
public class TestThread7{
public static void main(String[] args) {
//01模拟倒计时
// try {
// tenDown();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//02打印当前系统时间
Date startTime=new Date(System.currentTimeMillis());//获取当前时间
while (true){
try {
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
Thread.sleep(1000);
//更新时间
startTime=new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num=10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
线程礼让
礼让线程,让当前正在执行的线程暂停,但不阻塞
将线程从运行状态变为就绪状态
让CPU重新调度,礼让不一定成功,看CPU心情
/**
*线程礼让,礼让不一定成功
*/
public class TestThread8 {
public static void main(String[] args) {
MyYield myYield=new MyYield();
new Thread(myYield,"A").start();
new Thread(myYield,"B").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println("线程开始执行==="+Thread.currentThread().getName());
Thread.yield();//线程礼让
System.out.println("线程结束执行==="+Thread.currentThread().getName());
}
}
礼让成功
礼让不成功
线程强制执行
Join合并线程,待此线程执行完之后,再执行其他线程,其他线程阻塞
可以想象成插队
/**
*join合并线程
*/
public class TestThread10 implements Runnable{
@Override
public void run() {
for(int i=1;i<=5;i++){
System.out.println("vip=="+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动线程
TestThread10 testThread10=new TestThread10();
Thread thread=new Thread(testThread10);
thread.start();
//主线程
for(int i=1;i<=10;i++){
if(i==5){//主线程跑到100,插队线程进来,跑完他的100才会执行主线程
thread.join();//插队
}
System.out.println("main=="+i);
}
}
}
结果:
学习原视频:
多线程12:线程休眠_sleep_哔哩哔哩_bilibili