java多线程快速入门(十二)
在静态方法上面加synchonizd用的是字节码文件锁
package com.cppdy; class MyThread8 implements Runnable { private static Integer ticketCount = 100; public boolean falg = true; @Override public void run() { if (falg) { synchronized (MyThread8.class) { while (ticketCount > 0) { try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。"); ticketCount--; } } } else { while (ticketCount > 0) { sale(); } } } public static synchronized void sale() { if (ticketCount > 0) { try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。"); ticketCount--; } } } public class ThreadDemo8 { public static void main(String[] args) throws Exception { MyThread8 mt = new MyThread8(); Thread thread1 = new Thread(mt, "窗口1"); Thread thread2 = new Thread(mt, "窗口2"); thread1.start(); Thread.sleep(30); mt.falg = false; thread2.start(); } }
一般情况下,不使用static锁:JVM编译的时候,static是存到方法区,方法区是垃圾回收机制不会回收的