Java多线程(4)

JAVA学习网 2021-03-15 06:00:09

Java多线程

  • 本系列博客为学习Java多线程(狂神说)时所做的笔记
  • 本篇博客讲解线程的五大状态

五大状态

线程停止

  • JDK提供的stop()、destroy()已经不再被推荐使用
  • 推荐线程自己停下来
  • 建议使用一个标志位进行终止变量,当flag=false,则终止线程运行
//测试stop
//1.建议线程正常停止-->利用次数,不建议死循环
//2.建议使用标志位
//3.不要使用stop或destory等过时或者JDK不建议使用的方法
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++);
        }
    }
    //2.设置一个公开的方法停止线程,转换标志位

    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<1000;i++){
            System.out.println("main"+i);
            if (i==900){
                //调用stop方法,让现场停止
                testStop.stop();
                System.out.println("线程该停止了!");
            }
        }
    }
}

这里的线程停止,似乎并不是这个线程被杀死,只是表面上没有输出而已,继续学习先,回头再来看这个。

线程休眠

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

    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num<=0){
                break;
            }
        }
    }

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

这里讲了如何利用sleep来模拟网络延时。

线程礼让

  • 礼让线程,让当前正在执行的线程暂停,但是不阻塞
  • 将现场从运行状态转为就绪状态
  • 让CPU重新调度

所以这个线程礼让并不是真正意义上的礼让,可以理解为礼让的线程重新回到线程们的起跑线上,让CPU重新选择调度。所以,就有可能出现礼让成功和礼让不成功两种情况。

//测试礼让线程
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
        new Thread(myYield,"c").start();
    }
}
class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}

合并线程

  • Join合并线程,待此线程完成后,再执行其他线程
public class TestJoin implements Runnable{

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

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

        //主线程
        for (int i = 0; i < 1000; i++) {
            if (i==200){
                thread.join();
            }
            System.out.println(i+" "+"main");
        }
    }
}

这里有一个地方说得不清楚,主线程运行到join时,会让调用join的线程先执行完,再继续执行主线程。在join之前,主线程和调用join的线程交替执行,具体谁先看CPU心情。

线程状态观测

  • Thread.State

线程状态小汇总:

  1. NEW :尚未启动的线程处于此状态。
  2. RUNNABLE:在Java虚拟机中执行的线程处于此状态。
  3. BLOCKED: 被阻塞等待监视器锁定的线程处于此状态。
  4. WAITING: 正在等待另一个线程执行动作达到指导等待时间的线程处于此状态。
  5. 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("//////////////");
        });

        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);

        //观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state);


        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;
  • 使用以下方式改变或获取优先级
    • getPriority().setPriority(int xxx)
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,"1");
        Thread thread2 = new Thread(myPriority,"2");
        Thread thread3 = new Thread(myPriority,"3");
        Thread thread4 = new Thread(myPriority,"4");
        Thread thread5 = new Thread(myPriority,"5");
        Thread thread6 = new Thread(myPriority,"6");


        //设置优先级
        thread1.start();
        thread2.setPriority(1);
        thread2.start();
        thread3.setPriority(4);
        thread3.start();
//        thread4.setPriority(-1);
//        thread4.start();
//
//        thread5.setPriority(11);
//        thread5.start();

        thread6.setPriority(Thread.MAX_PRIORITY);
        thread6.start();

    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

优先级默认是5,而且优先级仅仅是有更高的先运行的可能性,总的还是看CPU心情,奇怪的是,我按照这个代码来运行,优先级10的线程没有一次先跑。

守护(daemon)线程

  • 线程分为用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如:后台记录操作日志,监控内存,垃圾回收等待
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        Thread thread = new Thread(god);
        thread.setDaemon(true);//正常的线程默为用户线程
        thread.start();

        ME me = new ME();

        new Thread(me).start();

    }
}

class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("上帝保护着你!");
        }
    }
}
class ME implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("你一生都开心的活着");
        }
        System.out.println("-====goodbye!world!====-");
    }
}
阅读(866) 评论(0)