码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA多线程Thread与Runnable

时间:2017-07-04 21:53:48      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:run   接口   rri   void   override   span   reads   color   code   

一、Runnable

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

 1 public class MyRunnable implements Runnable{
 2     @Override                                    //表示:预示重写方法
 3     public void run() {                            //实现接口run方法
 4         System.out.println("实现Runnable的线程0.0\t"+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\t"+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 }

运行结果

技术分享

JAVA多线程Thread与Runnable

标签:run   接口   rri   void   override   span   reads   color   code   

原文地址:http://www.cnblogs.com/-maji/p/7118274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!