zoukankan      html  css  js  c++  java
  • 线程控制

    一、线程休眠

      使用的方法:public static void sleep(long millis):让正在执行的线程休眠millis毫秒

      public static void sleep(long millis , int nanos):让正在执行的线程休眠millis毫秒加nanos纳秒

    public class Test implements Runnable{
        
        private String res = "test";
        public void run(){
            try {
                // 休眠1s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.print(res);
        }
    }

    二、线程加入

      使用的方法:public void join():等待该线程终止

      当对线程对象调用此方法时,只有当该线程执行完毕后其他线程才可以执行。

    public static void main(String[] args) {
            Test t = new Test();
            
            Thread t1 = new Thread(t);
            Thread t2 = new Thread(t);
            
            try {
                t1.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            t1.start();
            // t1执行完t2才执行
            t2.start();
        }

    三、线程礼让

      使用的方法:public static void yield():暂停当前正在执行的线程,执行其他线程

    public class Runable1Demo implements Runnable{
    
        public void run() {
            Thread.yield();
            System.out.println(Thread.currentThread().getName());
        }
        
    }

    四、守护线程

      使用的方法:public void setDaemon(boolean on):将该线程标记为守护线程或者是用户线程,on如果为true标记为守护线程。守护线程会在用户线程结束后被迫结束而不管有没有运行完,可以理解为守护线程守护服务于用户线程。

      

    public static void main(String[] args) {
            Test t = new Test();
            
            Thread t1 = new Thread(t);
            Thread t2 = new Thread(t);
            
            t1.setDaemon(true);
            
            t1.start();
            t2.start();
        }

    五、中断线程

      使用的方法:public void interrupt():中断线程。如果线程在调用Object类的wait()、wait(long)或wait(long ,int)方法,或者该类的join()、join(long)、join(long,int)、sleep(long)sleep(long,int)方法中受阻,则其中断状态被清除,它还将收到一个InterruptException。

  • 相关阅读:
    SpringBoot-14-MyBatis预热篇,MySQL小结
    SpringBoot-13-插曲之Node文件重命名+自动生成json对象
    八月十九风雨大作
    诉世书
    《仪式》
    珊瑚墓地
    新生
    《应龙》
    《枝·你是树的狂舞》
    golang中使用etcd
  • 原文地址:https://www.cnblogs.com/orlion/p/4833878.html
Copyright © 2011-2022 走看看