Java多线程之线程5种状态

1、五个状态

在这里插入图片描述

2、方法

setPriority(int newPriority)设置优先级
static void sleep(long millis)指定毫秒数内休眠
void join()线程的强制执行。(插队)
static void yield线程礼让,让当前执行的线程暂停。不一定会成功
void interrupt()中断线程
boolean isAlive()判断是否处于活动状态

3、停止线程

  • 不推荐使用stop() 和destroy()方法
  • 推荐线程自己停止下来
  • 建议使用一个标志位进行终止变量
    • flag == false
public class MyThreadSeven implements Runnable {
    //设置标志位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("run..." + i++);
        }
    }
    //定义stop()方法
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        
        MyThreadSeven myThreadSeven = new MyThreadSeven();
        new Thread(myThreadSeven).start();
        
        for (int i = 0; i < 20; i++) {
            
            System.out.println("main...."+i);
            
            if (i == 15) {
                myThreadSeven.stop();
                System.out.println("线程停止了");
            }
        }
    }
}

4、线程的休眠

  • sleep 存在异常
  • sleep是时间达到后,线程进入就绪状态
  • sleep可以模拟网络延时,倒计时等
    • 放大事情的发生性
  • 每个对象都有一个锁,sleep不会释放锁

public class MyThreadSleep {
    //倒计时
    public static  void down(int sec) {
        while(true){
            System.out.println(sec--);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (sec==0){
                break;
            }
        }
    }
    //网络延时
    public static void delay(){
        //获取当前时间
        Date startTime = new Date(System.currentTimeMillis());
        while (true){
            //格式工厂
            System.out.println(new SimpleDateFormat("yyyy-mm-dd HH:mm:ss").format(startTime));
            //一秒延时
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //更新时间戳
            startTime = new Date(System.currentTimeMillis());
        }
    }


    public static void main(String[] args) {
        // delay();
        down(10);
    }

龟兔赛跑例子
public class MyThreadFive implements Runnable {
    //胜利者
    private  static String WIN;
    @Override
    public void run() {

        for (int i = 1; i <=100; i++) {
            //兔子睡觉
            if(Thread.currentThread().getName().equals("兔子") && i%10==0){
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(getOver(i)){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }

    }
    //判断比赛是否结束。
    public boolean getOver(int step){
        if (WIN!=null){
            return true;
        }
        if(step==100){
            WIN = Thread.currentThread().getName();
            System.out.println(WIN+"赢了比赛");
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        MyThreadFive myThreadFive = new MyThreadFive();
        new Thread(myThreadFive,"兔子").start();
        new Thread(myThreadFive,"乌龟").start();
    }
}

5、线程的强制执行

public class MyThreadEight implements Runnable {

    @Override
    public void run() {

        for (int i = 0; i <100 ; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("插队"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadEight myThreadEight = new MyThreadEight();
        Thread thread = new Thread(myThreadEight);
        thread.start();

        for (int i = 0; i <50 ; i++) {
            Thread.sleep(10);
            if (i==20){
                thread.join();
            }
            System.out.println("mian...."+i);
        }
    }
}

6、线程的状态

NEW, RUNNABLE, WAITING, TIMED_WAITING, TERMINATED;
public class MyThreadNine {


    public static void main(String[] args) {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 3; 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 (state!=Thread.State.TERMINATED){
            System.out.println(state);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            state = thread.getState();
        }
        System.out.println(state);
    }
}
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
========
TERMINATED

7、线程优先级

public static final int MIN_PRIORITY = 1;

public static final int NORM_PRIORITY = 5;

public static final int MAX_PRIORITY = 10;
public class MyThreadTen implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        MyThreadTen myThreadTen = new MyThreadTen();
        Thread thread1 = new Thread(myThreadTen);
        Thread thread2 = new Thread(myThreadTen);
        Thread thread3 = new Thread(myThreadTen);
        //正常启动
        thread1.start();
        //设置成10
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread2.start();
        //设置成1
        thread3.setPriority(Thread.MAX_PRIORITY);
        thread3.start();
    }
}

Thread-2-->10
Thread-0-->5
Thread-1-->1

8、守护(daemon)线程

  • 线程分为用户线程 和 守护线程
  • JVM 必须确保用户线程执行完毕
  • JVM不用等待守护线程执行完毕
    • 后台操作日志 监控日志 垃圾回收
public class MyThreadEleven {
    public static void main(String[] args) {
        God god = new God();
        Human human = new Human();
        //启动上帝线程
        Thread thread = new Thread(god);
        //设置为守护线程,默认false 表示用户线程
        thread.setDaemon(true);
        thread.start();
        //人类线程
        new Thread(human).start();
    }
}

class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("守护!");
        }
    }
}
class Human implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("活着");
        }
        System.out.println("GoodBye!");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值