zoukankan      html  css  js  c++  java
  • Java多线程02

    线程五大状态

    新建 就绪 阻塞 运行 死亡

    线程停止

    package com.guanxing.state;
    
    //测试stop
    //1.建议线程正常停止--》利用次数,不建议死循环
    //2.建议使用标志位--》设置一个标志位
    //3.不要使用stop或destroy等过时的或JDK不建议使用的方法
    public class TestStop implements Runnable{
    
        //1.定义一个标识符
        private boolean flag = true;
    
        @Override
        public void run() {
            int i = 0;
            if (flag){
                System.out.println("run...Thread"+i++);
            }
        }
    
        //2.设置一个停止方法,切换标志位
        public void stop() {
            this.flag = false;
        }
    
        public static void main(String[] args) {
            TestStop ts01 = new TestStop();
            new Thread(ts01).start();
    
            for (int i = 0; i < 1000; i++) {
                System.out.println("main"+i);
                if (i==900) {
                    //调用stop方法
                    ts01.stop();
                    System.out.println("线程已停止...");
                }
            }
        }
    }
    

    线程休眠

    • sleep 指定当前线程阻塞的毫秒数
    • sleep 存在异常 InterruptedException
    • sleep 时间到达后线程进入就绪状态
    • sleep 可以模拟网络延时、倒计时等
    • 每一个对象都有一个锁,sleep 不会释放锁
    package com.guanxing.state;
    
    import javax.sound.midi.Track;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.SimpleFormatter;
    
    //sleep模拟倒计时
    public class TestSleep {
    
        public static void main(String[] args) {
            //打印当前系统时间
            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();
                }
            }
    
            //调用倒计时函数
    //        try {
    //            tenDown(10);
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //        }
        }
    
        public static void tenDown(int num) throws InterruptedException {
            while (num > 0) {
                Thread.sleep(1000);
                System.out.println(num--);
            }
        }
    }
    

    线程礼让

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

    线程抢占

    package com.guanxing.state;
    
    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 < 1000; i++) {
                if (i==200) {
                    try {
                        thread.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("main线程正在执行..."+i);
            }
        }
    }
    

    观测线程状态

    package com.guanxing.state;
    
    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);  //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);  //输出状态
            }
    
        }
    }
    
    /*
    NEW
    RUNNABLE
    TIMED_WAITING
    TIMED_WAITING
    ...
    TIMED_WAITING
    //////
    TERMINATED
    */
    

    线程优先级

    优先级用数字表示,范围从1~10

    使用以下方式改变或获取优先级

    • getPriority()
    • setPriority( int )
    package com.guanxing.state;
    
    public class TestPriority {
        public static void main(String[] args) {
            //先打印下main线程的
            System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    
            Priority priority = new Priority();
    
            //多创建几个线程
            Thread t1 = new Thread(priority);
            Thread t2 = new Thread(priority);
            Thread t3 = new Thread(priority);
            Thread t4 = new Thread(priority);
    
            //启动前先设置优先级
            t1.setPriority(4);
            t1.start();
    
            t2.setPriority(5);
            t2.start();
    
            t3.setPriority(1);
            t3.start();
    
            t4.setPriority(10);
            t4.start();
        }
    }
    
    class Priority implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
        }
    }
    
    /*
    main--->5
    Thread-3--->10
    Thread-1--->5
    Thread-0--->4
    Thread-2--->1
     */
    

    守护线程

    • 线程分为 用户线程守护线程
    • 虚拟机必须确保用户线程执行完毕
    • 虚拟机不必等待守护线程执行完毕
    • 如后台记录操作日志,监控内存,垃圾回收等等
    package com.guanxing.state;
    
    //测试守护线程
    //上帝保佑着你
    public class TestDaemon {
        public static void main(String[] args) {
            God god = new God();
            Person you = new Person();
    
            Thread godThread = new Thread(god);
            godThread.setDaemon(true);  //默认false表示用户线程,正常的线程都是用户线程...
            godThread.start(); //上帝守护线程启动
    
            new Thread(you).start(); //用户线程启动
        }
    }
    
    //定义一个上帝类
    class God implements Runnable {
        @Override
        public void run() {
            while (true) {
                System.out.println("上帝保佑着你!");
            }
        }
    }
    
    //定义一个人类
    class Person implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.println("每一天都要过的开开心心~");
            }
            System.out.println("========Goodbye World!========");
        }
    }
    
  • 相关阅读:
    前端带队之漫谈
    css3之currentColor
    安装及升级node
    谈JavaScript代码封装
    再玩儿一次——深入理解闭包
    【学习笔记】ES6标准入门
    【学习笔记】移动Web手册(PPK力作)
    使用webstorm操作git
    使用webstorm调试node程序
    前端代理nproxy
  • 原文地址:https://www.cnblogs.com/straightup/p/14503473.html
Copyright © 2011-2022 走看看