多线程详解:线程状态

线程状态

在这里插入图片描述

线程共包括以下5种状态。

  1. 新建状态(New) : 线程对象被创建后,就进入了新建状态。例如,Thread thread = new Thread()。

  2. 就绪状态(Runnable): 也被称为“可执行状态”。线程对象被创建后,其它线程调用了该对象的start()方法,从而来启动该线程。例如,thread.start()。处于就绪状态的线程,随时可能被CPU调度执行。

  3. 运行状态(Running) : 线程获取CPU权限进行执行。需要注意的是,线程只能从就绪状态进入到运行状态。

  4. 阻塞状态(Blocked) : 阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:

  • 等待阻塞 – 通过调用线程的wait()方法,让线程等待某工作的完成。
  • 同步阻塞 – 线程在获取synchronized同步锁失败(因为锁被其它线程所占用),它会进入同步阻塞状态。
  • 其他阻塞 – 通过调用线程的sleep()或join()或发出了I/O请求时,线程会进入到阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
  1. 死亡状态(Dead) : 线程执行完了或者因异常退出了run()方法,该线程结束生命周期。

在这里插入图片描述

线程方法

方法说明
final void setPriority(int newPriority)更改线程的优先级
static native void sleep(long millis)在指定的毫秒数内让当前正在执行的线程休眠
final void join()等待该线程终止
static native void yield();暂停当前正在执行的线程对象,并执行其他线程
void interrupt()中断线程,别用这种方式
boolean isAlive()测试线程是否处于活动状态

停止线程

  • 不推荐使用JDK提供的stop(),destroy()方法【已废弃】
  • 推荐线程自己停止下来(利用次数,不建议死循环)
  • 建议使用一个标志位进行终止变量,当flag=false,则终止线程运行

在这里插入图片描述
案例:

package lamada;

public class TestStop implements Runnable {

    //1.线程中定义线程体使用的标识
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("线程运行,执行run方法。。。Thread"+i++);
        }
    }

    //3.设置一个公开的方法停止线程,转化为标志符
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();

        for (int i = 0; i < 100; i++) {

            System.out.println("main 方法运行,i=" + i);

            if (i == 66) {
                //调用stop方法切换标志符,让线程停止
                testStop.stop();
                System.out.println("该线程停止了,i=" + i);
            }

        }
    }
}

线程休眠

  • sleep(时间)指定当前线程阻塞的毫秒数(1000毫秒=1s);
  • sleep存在异常InterruptedException;
  • sleep时间达到后线程进入就绪状态
  • sleep可以模拟网络延时,倒计时等
  • 每一个对象都有一个锁,sleep不会释放锁
1. 模拟网络延时:
package lamada;

//买火车的票的案例 多个线程同时操作同一个对象
//发现问题 :多个线程操作同一个资源的情况下,线程不安全,数据紊乱
//模拟网络延时: 放大问题的发生性
public class TestSleep implements Runnable {

    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNums <= 0) {
                break;
            }
            //模拟延时 0.2秒
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums-- + "票");
        }
    }

    public static void main(String[] args) {
        TestSleep ticketThread = new TestSleep();

        new Thread(ticketThread, "小明").start();
        new Thread(ticketThread, "老师").start();
        new Thread(ticketThread, "黄牛党").start();

    }
}

2. 模拟倒计时:
package lamada;

import sun.util.calendar.BaseCalendar;

import java.text.SimpleDateFormat;
import java.util.Date;

//模拟倒计时 10秒倒计时
public class TestSleep2 {
    
    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int time = 10;
        while (true) {
            //睡1s
            Thread.sleep(1000);
            System.out.println("倒计时:" + time--);
            if (time <= 0) {
                break;
            }
        }
    }

    //打印当前系统时间
    public static void PrintingTime() throws InterruptedException {
        Date startTime = new Date(System.currentTimeMillis());
        while (true) {
            Thread.sleep(1000);
            System.out.println("系统当前时间为  " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime));
            startTime = new Date(System.currentTimeMillis());
        }
    }

    public static void main(String[] args) {
        try {
            tenDown();
            PrintingTime();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

线程礼让

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转化为就绪状态
  • 让cpu重新调度,礼让不一定成功!看cpu心情
package lamada;

//测试礼让线程 礼让不一定成功
public class TestYield {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        new Thread(myThread,"A").start();
        new Thread(myThread,"B").start();
    }
}

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        //礼让
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程结束");
    }
}

礼让不一定成功!

在这里插入图片描述

在这里插入图片描述

线程强制执行 Join

  • Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
  • 可以想象成插队
package lamada;

//测试join方法 //想象为插队
public class TestJoin implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("线程vip来了" + i);
        }
    }

    public static void main(String[] args) {

        //启动线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 500; i++) {
            if (i == 10) {
                try {
                    System.out.println("我来插队了");
                    //插队 main线程阻塞
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("main 运行" + i);

        }
    }
}

在这里插入图片描述

观测线程状态

JDK文档

在这里插入图片描述

package lamada;

//观察测试线程的状态
public class TestState {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("/");
        });


        //观察状态
        Thread.State state = thread.getState();
        System.out.println("创建时:" + state);//NEW

        //观察启动后
        thread.start();//启动线程
        state = thread.getState();
        System.out.println("观察启动后:" + state);//Run

        while (state != Thread.State.TERMINATED) {//只要线程不终止,就一直输出
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println("输出状态:" + state);//输出状态

        }

    }
}

在这里插入图片描述

线程优先级

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级应该调度哪个线程来执行

  • 线程的优先级用数字来表示,范围从1-10

    • Thread.MIN_PRIORITY = 1;
    • Thread.MAX_PRIORITY = 10;
    • Thread.NORM_PRIORITY = 5;
  • 使用以下方式改变或获取优先级

    • int getPriority() 或者 void setPriority(int newPriority)
package lamada;

import javax.sound.midi.SoundbankResource;

public class TestPriority {

    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+" 主线程-->优先级:"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();

        Thread thread1 = new Thread(myPriority);
        Thread thread2 = new Thread(myPriority);
        Thread thread3 = new Thread(myPriority);
        Thread thread4 = new Thread(myPriority);
        Thread thread5 = new Thread(myPriority);
        Thread thread6 = new Thread(myPriority);

        //先设置优先级,再启动


        thread1.start();

        thread2.setPriority(1);
        thread2.start();

        thread3.setPriority(4);
        thread3.start();

        //Thread.MAX_PRIORITY = 10
        thread4.setPriority(Thread.MAX_PRIORITY);
        thread4.start();

        thread5.setPriority(8);
        thread5.start();


        thread6.setPriority(7);
        thread6.start();


    }
}


class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" 线程-->优先级:"+Thread.currentThread().getPriority());
    }
}

性能倒置

  • 优先级的设定建议在start()调度前
  • 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了。这都是看CPU的调度

在这里插入图片描述

守护(daemon)线程

  • 线程分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如,后台记录操作日志,监控内存,垃圾回收等待。。
package lamada;

//测试守护线程
//上帝保佑你
public class TestDaemon {

    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        //默认是false 表示是用户线程,正常的线程都是用户线程。。
        thread.setDaemon(true);
        //上帝守护线程启动
        thread.start();

        //you 用户线程启动。。
        new Thread(you).start();
    }
}


//上帝
class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("上帝保佑着你");
        }
    }
}

//我
class You implements Runnable{

    @Override
    public void run() {

        for (int i = 0; i < 35600; i++) {
            System.out.println("你每天都开心的活着");
        }
        System.out.println("==========game over  你离开了世界! goodbye=========");
    }
}

在这里插入图片描述

posted @ 2020-05-10 16:45  我有满天星辰  阅读(12)  评论(0编辑  收藏  举报