標籤:
線程是程式中一個單一的順序控制流程程。進程內一個相對獨立的、可調度的執行單元,是系統獨立調度和指派CPU的基本單位指運行中的程式的調度單位。在單個程式中同時運行多個線程完成不同的工作,稱為多線程。
進程(Process)是電腦中的程式關於某資料集合上的一次運行活動,是系統進行資源分派和調度的基本單位,是作業系統結構的基礎。
Java線程建立的兩種方式:
1.繼承Thread類
public class MyThread extends Thread{ private String name; public MyThread(String name) { this.name = name; } public void run() { try { for (int i = 0; i < 5; i++) { Thread.sleep(100); // 增加代碼執行時間 System.out.println("Thread " + this.name + ":" + i); } } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Thread thread1 = new MyThread("one"); Thread thread2 = new MyThread("two"); thread1.start(); thread2.start(); }}
輸出結果:
Thread one:0Thread two:0Thread two:1Thread one:1Thread one:2Thread two:2Thread one:3Thread two:3Thread one:4Thread two:4
2.實現介面Runnable
1 public class MyThread2 implements Runnable 2 { 3 private String name; 4 5 public MyThread2(String name) 6 { 7 this.name = name; 8 } 9 10 public void run()11 {12 try13 {14 for (int i = 0; i < 5; i++)15 {16 Thread.sleep(100); // 增加代碼執行時間17 System.out.println("Thread " + this.name + ":" + i);18 }19 }20 catch (InterruptedException e)21 {22 e.printStackTrace();23 }24 }25 26 public static void main(String[] args)27 {28 Thread thread1 = new Thread(new MyThread2("one"));29 Thread thread2 = new Thread(new MyThread2("two"));30 thread1.start();31 thread2.start();32 }33 }
輸出結果同上。
Java學習(九):Java線程的兩種實現方式