1. 程式人生 > >實現執行緒的兩種方式及其結合內部類的多種變態

實現執行緒的兩種方式及其結合內部類的多種變態

初學Java三十多天的小白,總結僅供參考!有錯誤希望大家踴躍指出,不勝感激!

實現執行緒的方式一:繼承Thread類

【1】正常形式下(最容易理解的形式)

public class TestDemo {
	public static void main(String[] args) {
		MyThread mt = new MyThread();
		mt.start();
	}
}

class MyThread extends Thread {
	public void run() {
		System.out.println("Something");
	}
}

【2】成員內部類

public class TestDemo {
	class MyThread extends Thread {
		public void run() {
			System.out.println("Something");
		}
	}

	public static void main(String[] args) {
		TestDemo td = new TestDemo();
		MyThread mt = td.new MyThread();
		mt.start();
	}
}

【3】區域性內部類

public class TestDemo {
	public static void main(String[] args) {
		class MyThread extends Thread {
			public void run() {
				System.out.println("Something");
			}
		}
		new MyThread().start();
	}
}

【4】匿名內部類
public class TestDemo {
	public static void main(String[] args) {
		new Thread() {
			public void run() {
				System.out.println("Something");
			}
		}.start();
	}
}

實現執行緒的方式一:實現Runnable介面

【1】正常形式下

public class TestDemo {
	public static void main(String[] args) {
		MyThread mt = new MyThread();
		Thread t = new Thread(mt);
		t.start();
	}
}

class MyThread implements Runnable {
	public void run() {
		System.out.println("Something");
	}
}

【2】成員內部類實現Runnable介面

public class TestDemo {
	class MyThread implements Runnable {
		public void run() {
			System.out.println("Something");
		}
	}

	public static void main(String[] args) {
		TestDemo td = new TestDemo();
		MyThread mt = td.new MyThread();
		Thread t = new Thread(mt);
		t.start();
	}
}

【3】區域性內部類實現Runnable介面

public class TestDemo {
	public static void main(String[] args) {
		class MyThread implements Runnable {
			public void run() {
				System.out.println("Something");
			}
		}
		MyThread mt = new MyThread();
		Thread t = new Thread(mt);
		t.start();
	}
}

【4】匿名內部類實現Runnable介面 由【3】演化

public class TestDemo {
	public static void main(String[] args) {
		Runnable r = new Runnable() {
			public void run() {
				System.out.println("Something");
			}
		};
		Thread t = new Thread(r);
		t.start();
	}
}

【5】匿名內部類實現Runnable介面(再簡化些)由【4】簡化

public class TestDemo {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			public void run() {
				System.out.println("Something");
			}
		}).start();

	}
}