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(类名)的方法来启动

     

     

     

     


     


     

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    linux stat 命令查看文件信息
    亟需为个人信息安全“保驾护航”
    CISSP认证考试CBK知识点变更分析
    CISM国际注册信息安全经理认证知识体系
    (ISC)² CISSP,SSCP官方知识域更新常见问题解答
    SQL函数大全——实例 yangan
    ArcGIS Server 体系结构(转) yangan
    DevExpress组件之——PopupMenu组件 yangan
    Visual Studio 2008 中工具箱丢失,解决方法 yangan
    Word文档内容无法选中以及点击鼠标无反应的问题(PowerDesigner 12.5 导致) yangan
  • 原文地址:https://www.cnblogs.com/penggy/p/4786512.html
Copyright © 2011-2022 走看看