下面我们来看看现Runable接口是不是实现了对象的共享吧, public class Sale {
public static void main(String[] args) { // TODO Auto-generated method stub Ticket t=Ticket.getInctance();//获取卖票实例 new Thread(t,"窗口1: ").start();//启动匿名卖票线程1,2,3,4 new Thread(t,"窗口2: ").start();//这里熟悉一下构造函数,参数别搞错了 new Thread(t,"窗口3: ").start(); new Thread(t,"窗口4: ").start();
} } class Ticket implements Runnable{//卖票类是实现Runnable接口 private static final Ticket t=new Ticket();//单例化 private Ticket(){} public static Ticket getInctance(){ return t; } private int tick=100;//共享的票 @Override public void run() {//卖票逻辑 // TODO Auto-generated method stub while(tick>0){ System.out.println(Thread.currentThread().getName()+"****"+tick--); } } }看看结果: 窗口1: ****4 窗口4: ****5 窗口3: ****6 窗口4: ****1 窗口1: ****2 窗口2: ****3
|