zoukankan      html  css  js  c++  java
  • 关于实现多线程的相关问题

    线程的实现有两种方式,一种是继承Thread类,一种是实现Runnable接口。

    1.使用继承Thread方法实现多线程。

     1  public class MyThread extends Thread{
     2       private int time;        //线程的休眠时间
     3       public MyThread(String name,int time){
     4           super(name);        //设置线程名称
     5            this.time = time;//设置线程时间
     6       }  
     7     public void run(){    //覆写run()方法
     8             try{
     9                 Thead.sleep(this.time);//指定休眠时间
    10             }catch(Exception e){
    11                 e.printStackTrace();
    12             }
    13             //输出信息
    14             System.out.println(Thread.currentThread().getName()+"线程休眠"+this.time+"毫秒");
    15     }    
    16  }  
    17  
     1 public class ThreadDemo
     2 {
     3     public static void main(String args[]){
     4         MyThread mt1 = new MyThread("线程1",10000);
     5 
     6         MyThread mt2 = new MyThread("线程2",10000);
     7 
     8         MyThread mt3 = new MyThread("线程3",10000);
     9 
    10         mt1.start();
    11         mt2.start();
    12         mt3.start();
    13     }
    14 }

    2.通过实现Runnable接口完成多线程操作。

     1 public MyThread implements Runnable{
     2     private String name;//线程名称
     3     private int time;    //线程时间
     4     public MyThread(String name,int time){
     5         this.name = name;//设置线程名称
     6         this.time = time;//设置线程时间
     7     }
     8     public void run(){//覆写run()方法
     9         try{
    10             Thread.sleep(this.time);//指定休眠时间
    11         }catch(Exception e){
    12             e.printStackTrace();
    13         }
    14         //输出信息
    15          System.out.println(this.name+"线程休眠"+this.time+"毫秒");
    16     }
    17 }
     1 public class ThreadDemo
     2 {
     3     public static void main(String args[]){
     4         MyThread mt1 = new MyThread("线程1",10000);//实例一个线程对象,指定休眠时间
     5 
     6         MyThread mt2 = new MyThread("线程2",20000);//实例一个线程对象,指定休眠时间
     7 
     8         MyThread mt3 = new MyThread("线程3",30000);//实例一个线程对象,指定休眠时间
     9 
    10         new Thread(mt1).start();//启动线程
    11 
    12         new Thread(mt2).start();//启动线程
    13 
    14         new Thread(mt3).start();//启动线程
    15     }
    16 }
  • 相关阅读:
    AngularJS--过滤器
    AngularJS--自定义指令和模板
    AngularJS多模块开发
    百度优先收录HTTPS网站?你的网站https还在等什么
    什么是HTTPS
    必须要懂得的密码技术
    如何处理服务器SSL收到了一个弱临时Diffie-Hellman 密钥?
    可以将代码签名证书安装在多台电脑上吗?
    学习第一天
    前端综合知识小集
  • 原文地址:https://www.cnblogs.com/zhengweicong/p/3138443.html
Copyright © 2011-2022 走看看