匿名内部类介绍:http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html
用Runnable模拟实现共享堆内存变量
import java.lang.Thread; public class SellTicket { /** * 用Runnable模拟实现共享堆内存变量 * @param args */ public static void main(String[] args) { Runnable runnable = new Runnable() { private int ticket = 50; public void run() { while (ticket > 0) { ticket--; System.out.println(Thread.currentThread().getName()+"当前票数为:" + ticket); } } }; new Thread(runnable).start(); new Thread(runnable).start(); } }
用Thread模拟实现共享堆内存变量
public class SellTicket2 { /** * 用Thread模拟实现共享堆内存变量 * @param args */ public static void main(String[] args) { Thread mt = new Thread(){ private int ticket = 50; public void run() { while (ticket > 0) { ticket--; System.out.println(Thread.currentThread().getName()+"当前票数为:" + ticket); } } }; new Thread(mt).start();; new Thread(mt).start();; } }
Runnable和Thread实现多线程,共同点是变量可以共享,区别是用借口实现更加灵活,继承只能单继承有局限性。