線程 實現的兩種方法
阿新 • • 發佈:2018-07-15
ble pac name runnable end extend 當前 ride xtend
1 package thread; 2 3 public class MyRunnable implements Runnable { 4 5 private int i = 1; 6 7 @Override 8 public void run() { 9 10 for (i = 1; i <= 100; i++) { 11 System.out.println(Thread.currentThread().getName() + " " + i);// 獲取當前運行的線程名稱 12 } 1314 } 15 16 }
1 package thread; 2 3 public class MyThread extends Thread { 4 5 private int i = 1; 6 7 @Override 8 public void run() { 9 10 for (i = 1; i <= 100; i++) { 11 System.out.println(Thread.currentThread().getName() + " " + i);// 獲取當前運行的線程名稱 12} 13 } 14 15 }
1 package thread; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 7 Thread t1 = new MyThread(); 8 Thread t2 = new MyThread();// 創建線程 9 10 t1.start(); 11 t2.start();// 就緒線程 12 13 Runnable r = newMyRunnable(); 14 15 Thread t3 = new Thread(r); 16 Thread t4 = new Thread(r);// 創建線程 17 18 t3.start(); 19 t4.start();// 就緒線程 20 21 } 22 23 }
線程 實現的兩種方法