实现线程的两种方式及其结合内部类的多种变态

初学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();

	}
}

猜你喜欢

转载自blog.csdn.net/luhongzheng/article/details/80058866