几种简洁创建线程的方式以及使用注意事项

匿名类

new Thread() {//创建方式1
	public void run() {
		for(int x=0; x<50; x++) {		
			System.out.println(Thread.currentThread().getName()+"....x="+x);
		}
	}
}.start();
 
Runnable r = new Runnable() {//创建方式2
	public void run() {	
		for(int x=0; x<50; x++) {		
			System.out.println(Thread.currentThread().getName()+"....z="+x);
		}
	}
};
new Thread(r).start();

Lambda

Runnable r = ()->{
	for(int x=0; x<50; x++){
		System.out.println(Thread.currentThread().getName()+"....z="+x);
	}
};
new Thread(r).start();

注意事项

事项1

class Test implements Runnable {
	public void run(Thread t){}
}
//如果错误 错误发生在哪一行?
//答案:错误在第一行,应该被abstract修饰,因为run()抽象方法没有被重写。

事项2

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

问题:在Thread方法中引入了一个多线程任务的参数,该参数重写了run()方式,同时又用匿名内部类的方式重写了run()方法。问,将会输出哪个?

答案:将会输出subThread run,必须以子类为主,若子类没有,在输出参数任务中的runnable run,若都没有,则执行Thread类中默认的run()方法。

猜你喜欢

转载自blog.csdn.net/FENGQIYUNRAN/article/details/84948860