JAVA多線程Thread與Runnable
阿新 • • 發佈:2017-07-04
ext -s ges this @override reads current ride art
一、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