Java多线程四:线程状态

线程五大状态

创建状态
就绪状态
阻塞状态
运行状态
死亡状态

停止线程

  • 不推荐使用JDK提供的stop()和destroy()方法。【已废弃】
  • 推荐线程自己停止下来
    建议使用一个标志位进行终止变量当flag=false,则终止线程运行。
public class TestStart 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) {
        TestStart testStart = new TestStart();
        new Thread(testStart).start();
        for (int i = 0; i < 100; i++) {
            System.out.println("main" + i);
            if (i == 50){
                testStart.stop();
                System.out.println("线程该停止了");
            }
        }
    }
}

线程休眠

  • sleep(时间)指定当前线程阻塞的毫秒数;
  • sleep存在异常InterruptedException;
  • sleep时间达到后线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等。
  • 每一个对象都有一个锁,sleep不会释放锁;
    模拟倒计时:
public class TestThread {
    public static void main(String[] args) throws InterruptedException {
        tenDown();
    }
    public static void tenDown() throws InterruptedException {
        int time = 10;
        while (time >= 0){
            Thread.sleep(1000);
            System.out.println(time-- );
        }
    }
}

获取当前系统时间:

public class TestTime {
    public static void main(String[] args) {
        Date startime = new Date(System.currentTimeMillis());//获取当前系统时间
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startime));
                startime = new Date(System.currentTimeMillis());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

线程礼让

  • 礼让线程,让当前正在执行的线程暂停但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让cpu重新调度,礼让不一定成功!
    代码演示;
public class TestYield implements Runnable{
    public static void main(String[] args) {
        TestYield yield = new TestYield();
        new Thread(yield,"a").start();
        new Thread(yield,"b").start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+ "线程停止执行");
    }
}

运行结果:
在这里插入图片描述
在这里插入图片描述

Join

  • Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
  • 可以想象成插队
    代码演示:
public class TestJoin implements Runnable{
    public static void main(String[] args) throws InterruptedException {
        TestJoin join = new TestJoin();
        Thread thread = new Thread(join);
        thread.start();
        for (int i = 0; i < 10; i++) {
            if (i == 5){
                thread.join();
            }
            System.out.println("主线程" + i);
        }
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("线程vip来了" + i);
        }
    }
}

结果:
在这里插入图片描述

线程状态观测

Thread.State
线程状态。线程可以处于以下状态之一:

  • NEW
    尚未启动的线程处于此状态。
  • RUNNABLE
    在Java虚拟机中执行的线程处于此状态。
  • BLOCKED
    被阻塞等待监视器锁定的线程处于此状态。
  • WAITING
    正在等待另一个线程执行特定动作的线程处于此状态。
  • TIMED_WAITING
    正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
  • TERMINATED
    已退出的线程处于此状态。
    一个线程可以在给定时间点处于一个状态。这些状态是不反映任何操作系统线程状态的虚拟机状态。
    代码:
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("666");
            }
        });
        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);//New
        //启动后
        thread.start();
        state = thread.getState();
        System.out.println(state);//Runnable
        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println(state);//TERMINATED
        }
    }
}

线程优先级

  • Java提供-个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
  • 线程的优先级用数字表示,范围从1~10.
    ◆Thread.MIN_ PRIORITY= 1;
    ◆Thread.MAX_ PRIORITY = 10;
    ◆Thread .NORM_ PRIORITY = 5;
  • 使用以下方式改变或获取优先级
    ◆getPriority() . setPriority(int xxx)

代码演示:

public class TestPriority {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
        Mediocrity mediocrity = new Mediocrity();
        Thread t1 = new Thread(mediocrity);
        Thread t2 = new Thread(mediocrity);
        Thread t3 = new Thread(mediocrity);
        Thread t4 = new Thread(mediocrity);
        Thread t5 = new Thread(mediocrity);

        t1.start();
        t2.setPriority(1);
        t2.start();
        t3.setPriority(5);
        t3.start();
        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();
        t5.setPriority(Thread.MIN_PRIORITY);
        t5.start();
    }
}
class Mediocrity implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
    }
}

代码结果:
在这里插入图片描述

守护线程

  • 线程分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如,后台记录操作日志,监控内存垃圾回收等待…
    代码演示:
public class TestDemo {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();
        Thread thread = new Thread(god);
        thread.setDaemon(true);//默认false表示用户线程,正常的线程都是用户线程
        thread.start();
        new Thread(you).start();
    }
}
class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("666");
        }
    }
}
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("带你飞");
        }
        System.out.println("带不动");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值