zoukankan      html  css  js  c++  java
  • 线程的休眠

    Thread类的实现

    class MyThread extends Thread{
     private int time;
     public MyThread (String name,int time){   //设置线程的名称和休眠时间;
      super(name); //得到线程的名称
      this.time = time;//得到线程和休眠时间单位毫秒
     }
     public void run(){
      try { //捕获异常
       Thread.sleep(this.time);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace(); //如果出现异常,则打印出来。
      }
      System.out.println(Thread.currentThread()//得到当前正在被执行的线程的引用
        .getName()+"休眠时间"+this.time+"毫秒");
     }
    }
    public class ExceDemo01 {
     public static void main(String[] args) {
      MyThread mt1 = new MyThread("线程A", 10000);  
      MyThread mt2 = new MyThread("线程B", 20000);
      MyThread mt3 = new MyThread("线程C", 30000);
      mt1.start();
      mt2.start();
      mt3.start();


     }
    }

    Runnable接口的实现

    class TheThread implements Runnable{
     private int time;
     private String name;
     public TheThread (String name,int time){   //设置线程的名称和休眠时间;
      this.name = name;  //得到线程的名称
      this.time = time;  //得到线程的休眠时间
     }
     public void run(){
      try {
       Thread.sleep(this.time);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace(); //如果出现异常,则打印出来。
      }
      System.out.println(this.name+"休眠时间"+this.time+"毫秒");
     }
    }
    public class ExceDemo02 {
     public static void main(String[] args) {
      TheThread mt1 = new TheThread("线程A", 10000);
      TheThread mt2 = new TheThread("线程B", 20000);
      TheThread mt3 = new TheThread("线程C", 30000);
      new Thread(mt1).start();
      new Thread(mt2).start();
      new Thread(mt3).start();

     

     }
    }

     

    两种方法的说明:

    多线程主要是用Thread类和Runnable接口来实现


    Thread类中对于线程的名称可以使用super(name)来得到;
    在打印输出的时候可以使用Thread.currentThread.getname()的方法来得到线程的名称;
    currentThread返回的是当前正在执行线程的引用
    线程可以直接使用类名.start方法直接运行

    Runnable中不存在super,所以线程的名称只能用this.name=name来实现
    线程的启动也不能使用start的方法,用new Thread(类名)的方法来启动

     

     

     

     


     


     

  • 相关阅读:
    GDAL GDALOpen 打开中文路径的问题
    (转载)星载SAR产品数据格式的介绍
    Qt 标题栏(标题、图标)设置
    android NDK与Cygwin配置
    从零开始系统深入学习android(实践让我们开始写代码Android框架学习7.通知)
    使用的Eclipise插件汇总
    android对话框弹出方式动画
    常用系统优化软件下载
    FLV 观看方法和视频文件转换攻略
    网络编辑如何应用SEO知识
  • 原文地址:https://www.cnblogs.com/penggy/p/7475867.html
Copyright © 2011-2022 走看看