標籤:shift 繼承 art print 重複 函數 基礎 方法 --
方式一: 繼承Thread類.
/* * main函數也叫主函數(也叫主線程), * 因為所有代碼的執行都是從這裡開始的. */ public static void main(String[] args) { // 在測試類別中,建立線程對象. MyThread mt1 = new MyThread(); // 開啟線程. //start() //mt1.run(); //如果調用run()方法, 只是普通的方法調用. mt1.start(); //開啟線程必須調用start()方法, 該方法會自動去調用run()方法. //mt1.start(); //同一線程不能重複開啟, 否則會報: IllegalThreadStateException異常. for (int i = 1; i <= 100; i++) { System.out.println("main...." + i); } } /** * 自訂的線程類: MyThread * @author * */// 1) 定義一個類(MyThread), 繼承Thread類.public class MyThread extends Thread{ //2) 重寫Thread#run(). @Override public void run() { //3) 把要執行的代碼放入run()方法中. for (int i = 1; i <= 100; i++) { System.out.println("run______________" + i); } }}
方式二: 實現Runnable介面.
public static void main(String[] args) { //格式化代碼: alt + shift + s --> 字母f // 在測試類別中, 建立Runnable介面的子類對象, MyRunnable mr = new MyRunnable(); // 並將其作為參數傳入Thread類的構造, 建立線程對象. Thread th = new Thread(mr); // 開啟線程. //start() th.start(); for (int i = 1; i <= 100; i++) { System.out.println("main***" + i); } } /** * Runnable介面的具體實作類別 * @author * *///1) 定義一個類(MyRunnable), 實現Runnable介面.public class MyRunnable implements Runnable { //2) 重寫Runnable#run(). @Override public void run() { //3) 把要執行的代碼放入run()方法中. for (int i = 1; i <= 100; i++) { System.out.println("run______________" + i); } }}
方式三: 結合線程池使用(實現Callable介面).
以後實現-_,
java基礎之多線程二:多線程實現方式