首页 > 代码库 > JAVA多线程Thread与Runnable
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。