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。

  • 相关阅读:
    Linux下升级gcc版本(9.1.0版本)
    Linux/CentOS系统同步网络时间的2种方法详解
    为什么使用promise
    总结js深拷贝和浅拷贝
    js闭包理解
    select框实现多选的功能
    动态添加element-ui组件
    总结鼠标移入移出事件
    echarts提示框太长,导致显示不全 ,撑大div框的问题
    vue项目中管理定时器
  • 原文地址:https://www.cnblogs.com/orlion/p/4833878.html
Copyright © 2011-2022 走看看