java匿名内部类一般是没有变量指向的对象,只能使用一次
如下代码,为了使用抽象类People的eat方法还要去继承然后复写eat方式,非常麻烦。对于接口也是如此。
package com.lubby.nosynchronizedtest; public abstract class People { public abstract void eat() ; }<pre name="code" class="java">package com.lubby.nosynchronizedtest; public class Teacher extends People { @Override public void eat() { System.out.println("老师正在吃饭"); } public static void main(String[] args) { People people = new Teacher(); people.eat(); } }
在看如下代码,是不是很简单。之间new一个
package com.lubby.nosynchronizedtest; public class Teacher { public static void main(String[] args) { new People() { @Override public void eat() { System.out.println("我正在吃饭"); } }.eat(); } }
仔细看看,发现是不是线程经常使用这种方法。线程的创建一般都是继承Threa抽象类或者Runable接口
package com.lubby.nosynchronizedtest; public class Teacher { public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { System.out.println("线程1正在跑"); } }; thread1.start(); } }
package com.lubby.nosynchronizedtest; public class Teacher { public static void main(String[] args) { Runnable runable = new Runnable() { @Override public void run() { System.out.println("run......."); } }; Thread thread = new Thread(runable); thread.start(); } }