Java中線程的創建有兩種方式:
1. 通過繼承Thread類,重寫Thread的run()方法,將線程運行的邏輯放在其中
2. 通過實現Runnable接口,實例化Thread類
一、通過繼承Thread類實現多線程
class MyThread extends Thread{ String name = null; int ticket = 0; public MyThread(String name){ this.name = name; } public synchronized void run(){ for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()+this.name+" ticket:"+ticket++); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
通過如下方式運行:
1 public static void main(String[] args) { 2 3 MyThread mThread1 = new MyThread("線程一"); 4 MyThread mThread2 = new MyThread("線程二"); 5 MyThread mThread3 = new MyThread("線程三"); 6 mThread1.start(); 7 mThread2.start(); 8 mThread3.start(); 9 }
運行結果如下:
1 Thread-1線程二 ticket:0 2 Thread-0線程一 ticket:0 3 Thread-2線程三 ticket:0 4 Thread-1線程二 ticket:1 5 Thread-0線程一 ticket:1 6 Thread-2線程三 ticket:1 7 Thread-1線程二 ticket:2 8 Thread-2線程三 ticket:2 9 Thread-0線程一 ticket:2 10 Thread-1線程二 ticket:3 11 Thread-2線程三 ticket:3 12 Thread-0線程一 ticket:3 13 Thread-1線程二 ticket:4 14 Thread-2線程三 ticket:4 15 Thread-0線程一 ticket:4
二、通過繼承Runnable接口實現多線程
多線程類:
1 class RunThread implements Runnable{ 2 3 int Counter = 0; 4 @Override 5 public synchronized void run() { 6 for(int i=0;i<5;i++){ 7 System.out.println(Thread.currentThread().getName()+"count:"+Counter++); 8 try { 9 Thread.sleep(100); 10 } catch (InterruptedException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } 14 } 15 } 16 }
實現方式:
1 public static void main(String[] args) { 2 3 RunThread rThread = new RunThread(); 4 Thread t1 = new Thread(rThread,"線程一"); 5 Thread t2 = new Thread(rThread,"線程二"); 6 Thread t3 = new Thread(rThread,"線程三"); 7 t1.start(); 8 t2.start(); 9 t3.start(); 10 }
輸出結果:
1 線程一count:0 2 線程一count:1 3 線程一count:2 4 線程一count:3 5 線程一count:4 6 線程二count:5 7 線程二count:6 8 線程二count:7 9 線程二count:8 10 線程二count:9 11 線程三count:10 12 線程三count:11 13 線程三count:12 14 線程三count:13 15 線程三count:14