JAVA多线程Thread与Runnable

Posted 云上咖啡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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\\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的主要内容,如果未能解决你的问题,请参考以下文章

4-5 《Java中多线程重点》——继承Thread实现Runnable死锁线程池Lambda表达式

Java多线程中Thread与Runnable的区别

JAVA多线程Thread与Runnable

Java中实现多线程继承Thread类与实现Runnable接口的区别

Java并发编程之六:Runnable和Thread实现多线程的区别(含代码)

JAVA笔记:多线程面试题整理!