package cc; // 同步的前提条件: //1、 同步需要两个或者两个以上的线程 //2、 多个线程使用的是同一个锁 // //同步的弊端:效率要相对慢一些,因为要不停地判断锁.此例就是利用了锁。 // //同步的两种表现形式: //1、 使用了同步代码块 //2、 同步函数。其实它的锁是this //注意:静态同步函数用的不是this。它用的是类文件对象。即xx.class。 // 尤其是在单例设计模式的那里尤其要注意这个问题!!!静态函数的同步 class Test4 { public static void main(String[] args) { Ticket4 t = new Ticket4();// 这里只建立了一个对象 Thread tr1 = new Thread(t); Thread tr2 = new Thread(t); Thread tr3 = new Thread(t); tr1.start(); tr2.start(); tr3.start(); } } class Ticket4 implements Runnable { Object object = new Object(); int num = 10; public void run() { while (true) { synchronized (object) { if (num > 0) { try { Thread.sleep(1000); } catch (Exception e) { e.toString(); } System.out.println(Thread.currentThread().getName() + "……现在卖出第" + num-- + "号票"); } } } } }