zoukankan      html  css  js  c++  java
  • JAVA多线程Thread与Runnable

    一、Runnable

      Runnable为一个之包含一个run方法的接口

     1 public class MyRunnable implements Runnable{
     2     @Override                                    //表示:预示重写方法
     3     public void run() {                            //实现接口run方法
     4         System.out.println("实现Runnable的线程0.0	"+Thread.currentThread().getName());
     5         
     6     }
     7     
     8     public static void main(String[] args) {
     9         //创建Runnable对象
    10         MyRunnable run = new MyRunnable();
    11         //以对象run为参数创建Thread对象
    12         Thread thr1 = new Thread(run,"线程-1");
    13         Thread thr2 = new Thread(run,"线程-2");
    14         Thread thr3 = new Thread(run,"线程-3");
    15         Thread thr4 = new Thread(run,"线程-4");
    16         Thread thr5 = new Thread(run,"线程-5");
    17         //启动线程
    18         thr1.start();
    19         thr2.start();
    20         thr3.start();
    21         thr4.start();
    22         thr5.start();
    23     }
    24 
    25 
    26 }

    运行结果为

    二、Thread

      Thread为一个实现了Runnable的类

     1 public class Threads extends Thread{
     2     //构造方法
     3     String name;
     4     Threads(String name){
     5         this.name = name;
     6     }
     7     //重写run方法
     8     public void run(){
     9         System.out.println("实现Runnable的线程0.0	"+Thread.currentThread().getName());
    10     }
    11 
    12     public static void main(String[] args) {
    13         //创建Treads对象
    14         Threads thr1 = new Threads("线程-1");
    15         Threads thr2 = new Threads("线程-2");
    16         Threads thr3 = new Threads("线程-3");
    17         Threads thr4 = new Threads("线程-4");
    18         Threads thr5 = new Threads("线程-5");
    19         //启动线程
    20         thr1.start();
    21         thr2.start();
    22         thr3.start();
    23         thr4.start();
    24         thr5.start();
    25 
    26     }
    27 
    28 }

    运行结果

  • 相关阅读:
    arm-linux-gcc-4.5.1的安装…
    OK6410之tftp下载内核,nfs…
    非常详细的ok6410的linux系统移植…
    2009-2010网络最热的 嵌入式…
    Vue-基础(二)
    【SpringBoot】Springboot1.5.9整合WebSocket
    Hadoop本地环境安装
    Vue-基础(一)
    【Jwt】JSON Web Token
    【JDK8】Java8 新增BASE64加解密API
  • 原文地址:https://www.cnblogs.com/-maji/p/7118274.html
Copyright © 2011-2022 走看看