Multithreading-thread stop, sleep, polite, observation, priority, guard (4)

Multithreading-thread stop, sleep, polite, observation, priority, guard (4)

  1. The five states of threads

Insert picture description here

  1. Thread stop

    • It is recommended to use threads to stop normally
    • It is recommended to use the flag bit -> set a flag bit
    • Do not use stop or destroy methods that are outdated or not recommended by the JDK
    //测试stop
    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("线程该停止了");
                }
            }
        }
    }
    
    
  2. Thread sleep

    • sleep (time) specifies the number of milliseconds that the current thread is blocked
    • Sleep has an exception InterruptedException
    • The thread enters the ready state after the sleep time is reached
    • sleep can simulate network delay, countdown, etc.
    • Every object has a lock, sleep will not release the lock (you will learn later, don’t worry)
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    //模拟倒计时
    public class TestSleep2 {
          
          
        public static void main(String[] args) {
          
          
           /* //打印倒计时
            try {
                tenDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
           //打印当前系统时间
            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();
                }
            }
        }
    
        //模拟倒计时
        public static void tenDown() throws InterruptedException {
          
          
            int num=10;
            while (true){
          
          
                Thread.sleep(1000);//倒计时10秒,每一次打印停一秒
                System.out.println(num--);
                if (num<0){
          
          
                    break;
                }
            }
        }
    }
    
    
  3. Thread Polite

    • Polite thread, so that the currently executing thread pauses, but does not block
    • Turn the thread from the running state to the ready state
    • Let the cpu reschedule, comity may not be successful, it depends on the cpu's mood.
    //测试礼让线程
    //礼让不一定成功,看cpu心情
    public class TestYield {
          
          
        public static void main(String[] args) {
          
          
            MyYield myYield=new MyYield();
    
            new Thread(myYield,"a").start();
            new Thread(myYield,"b").start();
    
        }
    
    }
    
    class MyYield implements Runnable{
          
          
    
        @Override
        public void run() {
          
          
            System.out.println(Thread.currentThread().getName()+"线程开始执行");
            Thread.yield();//礼让
            System.out.println(Thread.currentThread().getName()+"线程停止执行");
        }
    
    
  4. Thread Join

    • Join merge threads, after the execution of this thread is completed, execute other threads, and other threads are blocked
    • You can think of to jump the queue
    //测试join方法//想象为插队
    public class TestJoin implements Runnable {
          
          
    
        @Override
        public void run() {
          
          
            for (int i = 0; i < 1000; i++) {
          
          
                System.out.println("线程vip来了"+i);
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
          
          
    
            //启动我们的线程
            TestJoin testJoin=new TestJoin();
            Thread thread=new Thread(testJoin);
            thread.start();
    
            //主线程
            for (int i = 0; i < 500; i++) {
          
          
                if (i==200){
          
          
                    thread.join();//插队
                }
                System.out.println("main"+i);
            }
        }
    }
    
    
  5. Observe thread status

Insert picture description here

//观察测试线程的状态
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);//Run

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

       // thread.start();//死亡之后的线程就不能再次启动了

    }
}

  1. Thread priority

    • Java provides a thread scheduler that monitors all threads that enter the ready state after the program is started. The thread scheduler should schedule which thread to execute according to the priority.
    • The priority of the thread is represented by a number, ranging from 1-10
      • Thread.MIN_PRIORITY =1;
      • Thread.MAX_PRIORITY=10;
      • Thread.NORM_PRIORITY=5; (default)
    • Use the following methods to change or get priority
      • getPriority.setPriority(int xxx)
    • The low priority just means that the probability of getting the schedule is low, it is not that the low priority will not be called, it all depends on the CPU scheduling .
    //测试线程的优先级
    public class TestPriority extends Thread {
          
          
        public static void main(String[] args) {
          
          
            //主线程默认优先级 默认的优先级是5
            System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    
            MyPriority myPriority=new MyPriority();
    
            Thread t1=new Thread(myPriority);
            Thread t2=new Thread(myPriority);
            Thread t3=new Thread(myPriority);
            Thread t4=new Thread(myPriority);
            Thread t5=new Thread(myPriority);
            Thread t6=new Thread(myPriority);
    
            //先设置优先级,再启动
            t1.start();
    
            t2.setPriority(1);
            t2.start();
    
            t3.setPriority(4);
            t3.start();
    
            t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
            t4.start();
    
            t5.setPriority(8); //优先级是1-10之间。超过或小于都是错的
           t5.start();
    
            t6.setPriority(7);
            t6.start();
    
           /* t5.setPriority(-1); //优先级是1-10之间。超过或小于都是错的
           t5.start();
    
            t6.setPriority(11);
            t6.start();*/
        }
    
    }
    
    class MyPriority implements Runnable{
          
          
    
        @Override
        public void run() {
          
          
            System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
        }
    }
    
  2. Daemon thread

    • Threads are divided into user threads and daemon threads
    • The virtual machine must ensure that the user thread finishes execution
    • The virtual machine does not need to wait for the daemon thread to finish executing
    • For example, the background records the operation log, monitors the memory, and waits for garbage collection.
    //测试守护线程
    //上帝守护你
    public class TestDaemon {
          
          
        public static void main(String[] args) {
          
          
            God god=new God();
            You you=new You();
    
            Thread thread=new Thread(god);
            thread.setDaemon(true);//没写true之前,默认是false表示是用户线程,正常的线程都是用户线程..
    
            thread.start();//上帝守护线程启动
            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 < 36500; i++) {
          
          
                System.out.println("你一生都开心的活着");
            }
            System.out.println("==========goodbye! world==========");//Hello,World!
        }
    }
    

Guess you like

Origin blog.csdn.net/Xun_independent/article/details/114989733